Masterminds / sprig

Useful template functions for Go templates.
http://masterminds.github.io/sprig/
MIT License
4.06k stars 422 forks source link

Time Comparison Functions #372

Open kevin-lindsay-1 opened 1 year ago

kevin-lindsay-1 commented 1 year ago

Would be nice to have some time comparison functions.

For example, this doesn't work, and I don't see a way to do this using sprig as it stands, even though it provides some time support, albeit mostly formatting.

{{ $input := "2020-01-01" }}
{{ $inputDate := $input | toDate "2006-01-02" }}
{{ $currentDateString := now | date "2006-01-02" }}
{{ $currentDate := $currentDateString | toDate "2006-01-02" }}

{{ gt $currentDate $inputDate }}

this fails saying these types aren't comparable, and I don't see another function that can do this.

kevin-lindsay-1 commented 1 year ago

I also think that the distinctions between dates, times, date strings, and unix time can easily get confusing in terms of naming conventions.

For example, I think now returns a time.Time, and when people refer to date they often mean either a date string, or aren't specific. I'm not sure if toDate is actually a time.Time under the hood, but if so I think that could get a bit confusing as currently written.

kevin-lindsay-1 commented 1 year ago

I think I might be able to do this by first converting the value to a unix epoch and performing the comparison that way. Not exactly what I originally intended to do, but it might be a good workaround.

kevin-lindsay-1 commented 1 year ago

I was able to work around this using unixEpoch and then converting that to int64 and then performing a comparison.

I still think that this should be included as a good utility function, but if a maintainer wants to "won't" this, feel free to close.

isrealbm commented 11 months ago

incompatible types for comparison error means the types of 2 sides are incorrect. Just parse both of them become the same data types like: {{if gt (now | unixEpoch | int64) .CreatedAt }}.