12
2

More than 5 years have passed since last update.

momentでtimezoneを指定するときはmoment-timezoneを使う

Posted at

moment.jsでtimezoneを指定する方法

moment.jsでtimezoneを指定する場合はmoment.tz.setDefaultを使うのですが、momentモジュールを使うとtzがundefinedになっています。

const moment = require('moment');

console.log(moment.tz);
//-> undefined

tzを読み込めるように、moment-timezoneも読み込む必要があります。

const moment = require('moment');
require('moment-timezone');

console.log(moment.tz);
//-> objectがズラズラと表示される

// これでタイムゾーンを設定できる
moment.tz.setDefault('Asia/Tokyo');

これでもいいのですが、実はいきなりmoment-timezoneを読んでも使うことができます。

// momentではなくmoment-timezoneを読む
const moment = require('moment-timezone');

console.log(moment.tz);
//-> objectがズラズラと表示される

// これでタイムゾーンを設定できる
moment.tz.setDefault('Asia/Tokyo');

まとめ

以下の記事にちゃんとやり方は載っていたのですが変数名がmomentだったのでなかなか気づけませんでした・・・。

moment.jsのtimezoneを1行で日本に設定

意外とこの辺の記事が少なかったので誰かのお役に立てれば幸いです。

12
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
2