1use time::format_description::FormatItem;
2use time::macros::format_description;
3use time::{OffsetDateTime, PrimitiveDateTime};
4
5static ISO_8601_MILLIS_FORMAT: &[FormatItem<'static>] =
6 format_description!("[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:3]Z");
7static ISO_8601_SECONDS_FORMAT: &[FormatItem<'static>] =
8 format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]Z");
9
10static TASK_ID_TIMESTAMP_FORMAT: &[FormatItem<'static>] =
11 format_description!("[year][month][day]-[hour][minute][second]");
12
13pub fn now_utc() -> OffsetDateTime {
14 OffsetDateTime::now_utc()
15}
16
17pub fn format_iso_8601_millis(value: OffsetDateTime) -> String {
18 value
19 .replace_millisecond(value.millisecond())
20 .expect("millisecond replacement should stay in range")
21 .format(ISO_8601_MILLIS_FORMAT)
22 .expect("timestamp formatting should succeed")
23}
24
25pub fn parse_iso_8601_millis(value: &str) -> Result<OffsetDateTime, time::error::Parse> {
26 PrimitiveDateTime::parse(value, ISO_8601_MILLIS_FORMAT).map(PrimitiveDateTime::assume_utc)
27}
28
29pub fn parse_iso_8601_seconds(value: &str) -> Result<OffsetDateTime, time::error::Parse> {
30 PrimitiveDateTime::parse(value, ISO_8601_SECONDS_FORMAT).map(PrimitiveDateTime::assume_utc)
31}
32
33pub fn format_task_id_timestamp(value: OffsetDateTime) -> String {
34 value
35 .format(TASK_ID_TIMESTAMP_FORMAT)
36 .expect("task id timestamp formatting should succeed")
37}