cue-lang / cue

The home of the CUE language! Validate and define text-based and dynamic configuration
https://cuelang.org
Apache License 2.0
4.94k stars 279 forks source link

pkg/time: support conversion of time to unix #319

Open cueckoo opened 3 years ago

cueckoo commented 3 years ago

Originally opened by @rogpeppe in https://github.com/cuelang/cue/issues/319

Currently we can convert from unix seconds to RFC3339 but not vice-versa. It would also be nice to be able to add dates, etc.

cueckoo commented 3 years ago

Original reply by @antong in https://github.com/cuelang/cue/issues/319#issuecomment-775850587

I was looking for a way to write constraints on time fields, such as to require a field to be within a certain time range. I think having a function to convert to UNIX time would help. When you say "add dates, etc.", do you mean expose functions for time arithmetic like the Go time.Sub(), Add(), AddDate() and so on? I think that would be useful. And being able to convert to UNIX time would allow to do this with the durations that can already be parsed and validated by the time package.

About time constraints, If I understand correctly the time values as handled by the time package are actually RFC3339Nano formatted strings. (If this is so, we should probably document it. I didn't see it explicitly stated in the package doc.) As the doc says, RFC3339Nano doesn't necessarily sort correctly, so I feel a bit uneasy about that. But I guess it can only sort incorrectly between values that fall within the same second.

oncilla commented 2 years ago

I would like to work on this.

I propose the following usage:

import "time"

timestamp: "2021-08-04T18:37:48Z00:00"

unixTime: 1628102268
unixTime: time.ToUnix(timestamp) 

nanoTime: 1628102268 * 1G
nanoTime: time.ToUnixNano(timestamp) 

If you agree, let me know, and I can start working on this.

myitcv commented 2 years ago

Thanks for your interest, @oncilla - @mpvl and I will discuss at our next issue review session and revert back.