给定IANA时区和本地时间,将其解析为Maybe Posix?

问题描述 投票:4回答:2

有没有办法在Elm中使用当地时间(例如字符串2019-03-18T09:10:12.4;没有指定偏移量)和时区(例如Australia/Sydney)到可能的Posix值(即转换为UTC的时间),而不使用端口?


waratuman/time-extra,但它似乎只适用于Date部分。令人遗憾的是rtfeldman/elm-iso8601-date-strings不接受timezones

在JS中,有诸如moment-tzdate-fns-timezone之类的选项,但是避免JS interop进行频繁的日期解析会更简单。

datetime timezone utc elm
2个回答
2
投票

通过组合justinmimbs/time-extrajustinmimbs/timezone-data,您应该能够在Elm中完全获得有效的posix。

但是:Kua zxsw指出


首先,你需要将你的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,你可以得到一个posix值:

Zone

库作者建议您在模型中存储已评估的区域值:

toPosix : Time.Zone -> String -> Maybe Posix
toPosix zone timestampWithoutTimezone =
    timestampWithoutTimezone
        |> toParts
        |> Maybe.map (Time.Extra.partsToPosix zone)

2
投票

如果我们可以假设您的所有日期都没有时区,并且您总是希望在将它们转换为Posix之前将它们转换为model = { zone = TimeZone.australia__sydney () } toPosix model.zone "2019-03-18T09:10:12.4" ,那么您应该能够自己连接偏移以创建Australia/Sydney

2019-03-18T09:10:12.4+11:00
© www.soinside.com 2019 - 2024. All rights reserved.