在通常情况下,我建议在分类帐外进行字符串解析并在 asDate
和Time
类型中传递日期和时间,但听起来您需要在 DAML 中在分类帐上执行此操作。
您的第一个问题涉及将字符串解析为DA.Time
. 目前没有内置的通用日期/时间解析功能,因此您必须自己构建。对于像您这样的固定格式,模式匹配非常简单:
daml 1.2
module ParseTime where
import DA.Assert
import DA.Optional
import DA.Text
import DA.Time
import DA.Date
-- | `parseUTC` takes a string in the format "yyyyMMdd-HHmmss.SSS"
-- and converts it to `Time`, assuming the time is in UTC
-- Time is truncated to whole microseconds.
parseDateTimeUTC utc = datetime yy mon dd h m s `addRelTime` micros
where
-- Split out the micro seconds to stay under
-- pattern match complexity limit
[dt, ms] = splitOn "." utc
-- Pattern match on `explode` to check
-- the format and assign names to characters
[ y1, y2, y3, y4, mon1, mon2, d1, d2, "-",
h1, h2, ":", m1, m2, ":", s1, s2
] = explode dt
-- The function will fail on `fromSome` if any of the
-- integer strings don't parse
unsafeParse = fromSome . parseInt . implode
-- Map the parse function over grouped characters and
-- pattern match the result to give names to the Ints
[yy, imon, dd, h, m, s, imic] = map unsafeParse
[[y1, y2, y3, y4], [mon1, mon2], [d1, d2],
[h1, h2], [m1, m2], [s1, s2], explode $ T.take 6 ms]
-- Process month and microseconds into `Month` and
-- `Reltime` types
mon = toEnum $ imon - 1
mic = 10 ^ (max 0 (6 - T.length ms)) * imic
micros = convertMicrosecondsToRelTime mic
t = scenario do
let t = time (date 2018 Jun 05) 03 10 33 `addRelTime` convertMicrosecondsToRelTime 24075
parseDateTimeUTC "20180605-03:10:33.0240756" === t
要在DA.Time
微秒和微秒之间转换,我们需要选择时区。假设 UTC,我们可以定义
epochUTC = datetime 1970 Jan 1 0 0 0
microToTimeUTC n = epoch `addRelTime` convertMicrosecondsToRelTime n
timeToMicroUTC t = convertRelTimeToMicroseconds $ t `subTime` epoch
t2 = scenario do
microToTimeUTC 1557733583000000 === datetime 2019 May 13 07 46 23
timeToMicroUTC (datetime 2019 May 13 07 46 23) === 1557733583000000
在日期之间转换DA.Time
和Int
表示。
如果您想要现有 的微秒组件DA.Time
,您只需要微秒表示的最后六位数字:
micros t = timeToMicroUTC t % 1000000
t3 = scenario do
micros (parseDateTimeUTC "20180605-03:10:33.0240756") === 24075
注意这里截断到整微秒,这也在parseDateTimeUTC
.