Skip to content

Commit

Permalink
Add timezone() builtin
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed May 7, 2024
1 parent 9207e71 commit 1f31cc5
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
11 changes: 11 additions & 0 deletions builtin/builtin.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
2 changes: 2 additions & 0 deletions builtin/builtin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down
32 changes: 32 additions & 0 deletions docs/language-definition.md
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down

0 comments on commit 1f31cc5

Please sign in to comment.