Skip to content

Commit

Permalink
add toDate function
Browse files Browse the repository at this point in the history
  • Loading branch information
andreynering committed Sep 7, 2017
1 parent 175e437 commit 782a011
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 0 deletions.
5 changes: 5 additions & 0 deletions date.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,8 @@ func dateAgo(date interface{}) string {
duration := time.Since(t) / time.Second * time.Second
return duration.String()
}

func toDate(fmt, str string) time.Time {
t, _ := time.ParseInLocation(fmt, str, time.Local)
return t
}
7 changes: 7 additions & 0 deletions date_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,10 @@ func TestAgo(t *testing.T) {
t.Error(err)
}
}

func TestToDate(t *testing.T) {
tpl := `{{toDate "2006-01-02" "2017-12-31" | date "02/01/2006"}}`
if err := runt(tpl, "31/12/2017"); err != nil {
t.Error(err)
}
}
12 changes: 12 additions & 0 deletions docs/date.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,15 @@ Same as htmlDate, but with a timezone.
htmlDate (now) "UTC"
```

## toDate

`toDate` converts a string to a date. The first argument is the date layout and
the second the date string. If the string can't be convert it returns the zero
value.

This is useful when you want to convert a string date to another format
(using pipe). The example below converts "2017-12-31" to "31/12/2017".

```
toDate "2006-01-02" "2017-12-31" | date "02/01/2006"
```
1 change: 1 addition & 0 deletions functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ var genericMap = map[string]interface{}{
"dateInZone": dateInZone,
"dateModify": dateModify,
"ago": dateAgo,
"toDate": toDate,

// Strings
"abbrev": abbrev,
Expand Down

0 comments on commit 782a011

Please sign in to comment.