Javascript: Get current date time in yyyy/MM/dd HH:mm:ss format

Last updated on February 13, 2022 A Goodman Loading... One comment

This concise article shows you how to get the current date and time in Javascript in yyyy/MM/dd HH:mm:ss format. We’ll write code from scratch without using any third-party libraries.

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

The code:

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}`;

When running the code, you will receive a result like so:

2022/01/13 14:13:20

That’s it. Further reading:

I have made every effort to ensure that every piece of code in this article works properly, but I may have made some mistakes or omissions. If so, please send me an email: [email protected] or leave a comment to report errors.

Notify of
1 Comment
Inline Feedbacks
View all comments
8 months ago

Thanks, I just noticed that the months should be +1.

Related Articles