From 1f31cc5a5e412d6444fc95a2aa414a8e2d2f3f8d Mon Sep 17 00:00:00 2001 From: Anton Medvedev Date: Tue, 7 May 2024 21:36:22 +0200 Subject: [PATCH] Add timezone() builtin --- builtin/builtin.go | 11 +++++++++++ builtin/builtin_test.go | 2 ++ docs/language-definition.md | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+) diff --git a/builtin/builtin.go b/builtin/builtin.go index 1199f59c..4995e75c 100644 --- a/builtin/builtin.go +++ b/builtin/builtin.go @@ -529,6 +529,17 @@ var Builtins = []*Function{ new(func(string, string, string) time.Time), ), }, + { + Name: "timezone", + Func: func(args ...any) (any, error) { + tz, err := time.LoadLocation(args[0].(string)) + if err != nil { + return nil, err + } + return tz, nil + }, + Types: types(time.LoadLocation), + }, { Name: "first", Func: func(args ...any) (any, error) { diff --git a/builtin/builtin_test.go b/builtin/builtin_test.go index dca4bccf..fc2395f7 100644 --- a/builtin/builtin_test.go +++ b/builtin/builtin_test.go @@ -116,6 +116,8 @@ func TestBuiltin(t *testing.T) { {`date("2023-04-23T00:30:00.000+0100", "2006-01-02T15:04:05-0700", "America/Chicago").Format("2006-01-02")`, "2023-04-22"}, {`date("2023-04-23T00:30:00", "2006-01-02T15:04:05", "America/Chicago").Format("2006-01-02")`, "2023-04-23"}, {`date("2023-04-23", "2006-01-02", "America/Chicago").Format("2006-01-02")`, "2023-04-23"}, + {`timezone("UTC").String()`, "UTC"}, + {`timezone("Europe/Moscow").String()`, "Europe/Moscow"}, {`first(ArrayOfString)`, "foo"}, {`first(ArrayOfInt)`, 1}, {`first(ArrayOfAny)`, 1}, diff --git a/docs/language-definition.md b/docs/language-definition.md index 8e22d3b6..251f8455 100644 --- a/docs/language-definition.md +++ b/docs/language-definition.md @@ -484,6 +484,38 @@ date("2023-08-14T00:00:00Z") date("2023-08-14 00:00:00", "2006-01-02 15:04:05", "Europe/Zurich") ``` +Available methods on the date: + +- `Year()` - returns the year +- `Month()` - returns the month (starting from 1) +- `Day()` - returns the day of the month +- `Hour()` - returns the hour +- `Minute()` - returns the minute +- `Second()` - returns the second +- `Weekday()` - returns the day of the week +- `YearDay()` - returns the day of the year +- and [more](https://pkg.go.dev/time#Time). + +```expr +date("2023-08-14").Year() == 2023 +``` + +### timezone(str) {#timezone} + +Returns the timezone of the given string `str`. List of available timezones can be +found [here](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + +```expr +timezone("Europe/Zurich") +timezone("UTC") +``` + +To convert a date to a different timezone, use the [`In()`](https://pkg.go.dev/time#Time.In) method: + +```expr +date("2023-08-14 00:00:00").In(timezone("Europe/Zurich")) +``` + ## Number Functions ### max(n1, n2) {#max}