5
4

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 5 years have passed since last update.

javascriptで日時のタイムスタンプ文字列を生成する

Posted at

JavaScriptだけでDateをフォーマットするのは面倒です(0埋めが必要だったり、getMonthが0-11を返すとか・・・)

moment.jsを使うがお勧めですが、手元でちょいとフォーマットしたい的な際のサンプルです。

    // 現在日時からタイムスタンプのファイル名を生成
    const d = new Date(); // Today
    const DateTimeFormat = 'YYYYMMDD_hhmiss'; // "2019/10/04 12:34:56" -> "20191004_123456"
    let toFileName = DateTimeFormat
      .replace(/YYYY/g, String(d.getFullYear()))
      .replace(/MM/g, ('0' + (d.getMonth() + 1)).slice(-2))
      .replace(/DD/g, ('0' + d.getDate()).slice(-2))
      .replace(/hh/g, ('0' + d.getHours()).slice(-2))
      .replace(/mi/g, ('0' + d.getMinutes()).slice(-2))
      .replace(/ss/g, ('0' + d.getSeconds()).slice(-2));

DateTimeFormat文字列を変更すれば、お好きな形式に整形できます。

    const DateTimeFormat = 'YYYY/MM/DD hh:mi:ss'; // "2019/10/04 12:34:56" -> "2019/10/04 12:34:56"
5
4
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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?