Elm中是否有一种方法可以将本地时间(例如字符串2019-03-18T09:10:12.4
; 没有指定偏移量)和时区(例如Australia/Sydney
)转换为可能的Posix值(即,该时间已转换为UTC),而无需使用端口?
有waratuman/time-extra,但它似乎仅适用于Date部分。遗憾的是rtfeldman/elm-iso8601-date-strings不接受timezones。
在JS中,有诸如moment-tz和date-fns-timezone之类的选项,但是避免JS互操作进行频繁的日期解析会更加简单。
最佳答案
通过组合justinmimbs/time-extra和justinmimbs/timezone-data,您应该可以完全在Elm中获得有效的posix。
演示:https://ellie-app.com/54tyw9yvsQga1
首先,您需要将timestampWithoutTimezone
转换为 Parts
:
toParts : String -> Maybe Parts
toParts timestampWithoutTimezone =
timestampWithoutTimezone
|> Regex.find regex
|> List.map .submatches
|> List.head
|> Maybe.andThen Maybe.Extra.combine
|> Maybe.andThen listToParts
regex : Regex
regex =
Maybe.withDefault Regex.never <|
Regex.fromString "^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d)$"
monthLookup : Dict String Month
monthLookup =
Dict.fromList [ ( "01", Jan ), ( "02", Feb ), ( "03", Mar ), ( "04", Apr ), ( "05", May ), ( "06", Jun ), ( "07", Jul ), ( "08", Aug ), ( "09", Sep ), ( "10", Oct ), ( "11", Nov ), ( "12", Dec ) ]
listToParts : List String -> Maybe Parts
listToParts list =
let
toInt : Int -> Maybe Int
toInt index =
list |> List.Extra.getAt index |> Maybe.andThen String.toInt
in
Maybe.map2 Parts
(toInt 0)
(list |> List.Extra.getAt 1 |> Maybe.andThen (\month -> Dict.get month monthLookup))
|> Maybe.andThen (\parts -> Maybe.map5 parts (toInt 2) (toInt 3) (toInt 4) (toInt 5) (toInt 6))
然后,将
partsToPosix
与适当的 Zone
结合使用,您可以获得posix值:toPosix : Time.Zone -> String -> Maybe Posix
toPosix zone timestampWithoutTimezone =
timestampWithoutTimezone
|> toParts
|> Maybe.map (Time.Extra.partsToPosix zone)
库作者建议您将评估的Zone值存储在模型中:
model = { zone = TimeZone.australia__sydney () }
toPosix model.zone "2019-03-18T09:10:12.4"
关于datetime - 给定IANA时区和本地时间,将其解析为Maybe Posix?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55271388/