12
9

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

【Node.js】現在日時を取得する方法4選

Last updated at Posted at 2021-01-08

目標

Node.jsで現在日時をYYYYMMDDHHmmssの14桁のフォーマットで出力します。
nodeコマンドで下記のような出力が得られるプログラムですね。

$ node index.js
202101082341

前提

Node.js 14.15.4
date-utils 1.2.21
moment 2.29.1

更新情報

【2020/01/09 toLocaleStringメソッドを利用 追加】
@il9437 様、ありがとうございます!

Javascriptで頑張る

index.js
const date = new Date();
const currentTime = formattedDateTime(date);
console.log(currentTime)

function formattedDateTime(date) {
  const y = date.getFullYear();
  const m = ('0' + (date.getMonth() + 1)).slice(-2);
  const d = ('0' + date.getDate()).slice(-2);
  const h = ('0' + date.getHours()).slice(-2);
  const mi = ('0' + date.getMinutes()).slice(-2);
  const s = ('0' + date.getSeconds()).slice(-2);

  return y + m + d + h + mi + s;
}

date-utiliesを利用

index.js
require('date-utils');
const date = new Date();
const currentTime = date.toFormat('YYYYMMDDHH24MISS');
console.log(currentTime);

Moment.jsを利用

index.js
const moment = require('moment');
const currentTime = moment();
console.log(currentTime.format("YYYYMMDDHHmmss"));

toLocaleStringメソッドを利用 (@il9437 様からのご教示)

記事を出した時点では上記のやり方で実装する必要があるとの認識でしたが、
@il9437 様にtoLocaleStringメソッドでスウェーデン語を指定してから加工する効率的な方法を教えて頂いたので記事内でも紹介します

index.js
const date = new Date().toLocaleString('sv').replace(/\D/g, '');
console.log(date);
12
9
4

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
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?