0
0

JavaScriptで現在の日時を取得する

Posted at

日付と時刻

呼び出すときに例えば今日の日付をnew Date()で生成して引数で渡します。

呼び出し側
const fileGenDate = this.formatDate(new Date()); // ファイル生成日時 YYYYMMDD_hhmm

YYYYMMDD_hhmmssの形式で取得します。

定義側
public formatDate(date: Date): string {
		const year = date.getFullYear().toString(); // YYYY
		const month = (date.getMonth() + 1).toString().padStart(2, '0'); // MM getMonth()は0から数えるため+1が必要
		const day = date.getDate().toString().padStart(2, '0'); // DD
		const hours = date.getHours().toString().padStart(2, '0'); // hh
		const minutes = date.getMinutes().toString().padStart(2, '0'); // mm
		const seconds = date.getSeconds().toString().padStart(2, '0'); // ss
		
        return `${year}${month}${day}_${hours}${minutes}`; // YYYYMMDD_hhmm
	}

Date オブジェクトが持つ値から日付と時刻の値をそれぞれ取得するメソッドとして次のものが用意されています。

メソッド
getFullYear()      // 年の値を取得する
getMonth()         // 月の値を取得する
getDay()           // 曜日の値を取得する
getHours()         // 時の値を取得する
getMinutes()       // 分の値を取得する
getSeconds()       // 秒の値を取得する
getMilliseconds()  // ミリ秒の値を取得する

padStart()、padEnd()は文字列にのみ使用できるメソッド。

'5'.padStart(2, '0'); // 5の場合、"05"
'5'.padEnd(2, '0'); // 5の場合、"50"
// (2, '0')の2は桁数、'0'は2桁に満たない場合に前0を付与する
'abc'.padStart(7, '@'); // "@@@@abc"のようにabcの前に@が付与し7文字列になる
'abc'.padEnd(7, '@'); // "abc@@@@"のようにabcの後に@が付与し7文字列になる
0
0
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
0
0