twigjs / twig.js

JS implementation of the Twig Templating Language
BSD 2-Clause "Simplified" License
1.88k stars 275 forks source link

Time zone support #496

Open rktyt opened 7 years ago

rktyt commented 7 years ago

nodejs6.11 Server's timezone is UTC.

js:

process.env.TZ='Asia/Tokyo'

twig:

{{'now'|date('Y-m-d H:i:s')}}
{{'now'|date('Y-m-d H:i:s', 'Asia/Tokyo')}}
{{'2017-09-11T08:43:02.535Z'|date('Y-m-d H:i:s')}}
{{'2017-09-11T08:43:02.535Z'|date('Y-m-d H:i:s', 'Asia/Tokyo')}}

Always shown in UTC.


updated

Sorry, the problem that process.env.TZ did not work was caused by babel-node. However, the second argument of date filter is not working.

EvanK commented 5 years ago

FWIW, I needed to convert dates (in the local server timezone) to ISO 8601 in UTC, and managed it with a (somewhat hacky) filter:

Twig.extendFilter("date_c_utc", (input) => {
  const offsetSecs = input.getTimezoneOffset() * 60000
  const offsetDate = new Date(input.getTime() + offsetSecs)

  return Twig.filters.date(offsetDate, ["Y-m-d\\TH:i:s+00:00"])
})

To get these outputs (first in my local PST tz, second in UTC with a fibbed tz offset):

{{ currentDateTime | date("c") }} # outputs 2019-02-11T13:33:32-08:00
{{ currentDateTime | date_c_utc }} # outputs 2019-02-11T21:33:11+00:00
ericmorand commented 5 years ago

Well, based on the source code for the date filter, I assume the second argument is not supported:

date: function(value, params) {
        var date = Twig.functions.date(value);
        var format = params && params.length ? params[0] : 'F j, Y H:i';
        return Twig.lib.date(format.replace(/\\\\/g, '\\'), date);
},