LoginSignup
3
2

More than 3 years have passed since last update.

Unixtimeから(秒かミリ秒から)momentを作る時の注意点

Last updated at Posted at 2019-11-25

momentの作成

秒からmomentを作る時に

もしくは

ミリ秒からmomentを作る時に

ドキュメンテーションが書いてある通り、ローカルモードmomentが作られる。

つまり、コードが動いている環境のタイムゾーンで作られる

Docker環境が日本時間ではなく、デフォルトのUTC時間になっている可能性があるので注意しないといけない。

moment.unix(1519200000)
  .format(dateutils.FORMAT.MYSQL_DATETIME); // ==> "YYYY-MM-DD HH:mm:ss"

// 2018-02-21 08:00:00 になってしまうけども、日本時間だと 17:00:00 が正しい

なので、日本時間を期待している時に、utcOffsetを使わないといけない。

moment.unix(1519200000)
  .utcOffset(config.timezones[config.timezone].hour) // "+09:00"
  .format(dateutils.FORMAT.MYSQL_DATETIME); // "YYYY-MM-DD HH:mm:ss"

// 正しく 2018-02-21 17:00:00 になる

結論

  • ミリ秒だとそのまま渡せる
  • 秒だと、* 1000して渡すこと
date2moment(VALUE_IN_MILLISECONDS);
date2moment(VALUE_IN_SECONDS * 1000);

type DateLike = Date | number | string | null;

function date2moment(date: DateLike = null): moment.Moment {
    const unixtime = _getUnixtime(date);
    const hour = config.timezones[config.timezone].hour;
    return moment(unixtime).utcOffset(hour);
}

function _getUnixtime(date: DateLike): number {
    if (date === null) {
        return Date.now();
    }
    if (typeof date === "number") {
        return date;
    }
    if (date instanceof Date) {
        return date.getTime();
    }
    if (typeof date === "string") {
        return new Date(date).getTime();
    }

    throw new TypeError(`"${date}" must be a NULL or Number or Date`);
}
3
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
3
2