2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Javascript - よく見るタイムスタンプを出力するコード

Last updated at Posted at 2019-12-17

yyyy-MM-dd hh:mm:ssを出力するコード。

function timestamp(){
  function twoDigits(t){return ("0"+t).slice(-2);}

  var date = new Date();
  var year = date.getFullYear();
  var month = twoDigits(date.getMonth() + 1);
  var day = twoDigits(date.getDate());
  var hour = twoDigits(date.getHours());
  var minutes = twoDigits(date.getMinutes());
  var seconds = twoDigits(date.getSeconds());

  return [year,month,day].join("-")+" "+[hour,minutes,seconds].join(":");
};

↓ 実行結果

2019-12-09 17:59:05
  • Google Tag Manager(MTG)で使う想定なので変数定義は「const」ではなく「var」
  • 月・日・時・分・秒が1桁のときはゼロも追加されて2桁になる。
  • 参考記事:JavaScriptで日付や時間の0詰めを実装する
  • toLocaleTimeStringを使えば時・分・秒をまとめて出力できるが、環境によって「9:33:19 AM」のようなフォーマットになることもあるのであえて使わない

検討メモ(追記

UTC -> JST も考慮

GTMじゃないなら、、

function timestamp() {
    const date = new Date();
    const dtf = new Intl.DateTimeFormat('en-US', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false,
      timeZone: 'Asia/Tokyo'
    });

    const [{ value: mo }, , { value: da }, , { value: ye }, , { value: ho }, , { value: mi }, , { value: se }] = dtf.formatToParts(date);

    const year = ye;
    const month = mo;
    const day = da;
    const hour = ho;
    const minutes = mi;
    const seconds = se;

    return [year, month, day].join("-") + " " + [hour, minutes, seconds].join(":");
}

GTMなら、、

GTMだと機能制限あるから、JSTに変換するために、Date().getTimezoneOffset()はブラウザの現在のタイムゾーンとUTCとの差を計算して9時間足すみたいなことが必要だけど、UTC以外の場合は誤差が出てしまう。どうしたものか

function timestamp() {
    var now = new Date(Date.now() + ((new Date().getTimezoneOffset() + (9 * 60)) * 60 * 1000));
    var pad = function(num) {
    var norm = Math.abs(Math.floor(num));
        return (norm < 10 ? '0' : '') + norm;
        };
    return now.getFullYear()
    + '-' + pad(now.getMonth()+1)
    + '-' + pad(now.getDate())
    + ' ' + pad(now.getHours())
    + ':' + pad(now.getMinutes())
    + ':' + pad(now.getSeconds())
}
2
2
1

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?