Javascript: Get current date time as 20xx/00/00 00:00:00 format

February 9, 2020 Goodman Loading... Post a comment

In this tutorial, we will create a new Date object then use the getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds() methods to get the current date-time in Javascript. To make sure the month, date, hour, minute, second always are two-character format, we will a string method: slice().

Input:

const dateObj = new Date();

let year = dateObj.getFullYear();

let month = dateObj.getMonth();
month = ('0' + month).slice(-2);
// To make sure the month always has 2-character-formate. For example, 1 => 01, 2 => 02

let date = dateObj.getDate();
date = ('0' + date).slice(-2);
// To make sure the date always has 2-character-formate

let hour = dateObj.getHours();
hour = ('0' + hour).slice(-2);
// To make sure the hour always has 2-character-formate

let minute = dateObj.getMinutes();
minute = ('0' + minute).slice(-2);
// To make sure the minute always has 2-character-formate

let second = dateObj.getSeconds();
second = ('0' + second).slice(-2);
// To make sure the second always has 2-character-formate

const time = `${year}/${month}/${date} ${hour}:${minute}:${second}`;
console.log(time); 

Output:

2020/01/09 20:47:32
avatar

Related Articles