Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

I need to output the current UTC datetime as a string with the following format:
YYYY/mm/dd hh:m:sec

How do I achieve that with Javascript?

like image 545
sarsnake Avatar asked Dec 02 '11 21:12

sarsnake


People also ask

How do you display the current date in JavaScript?

In JavaScript, we can easily get the current date or time by using the new Date() object. By default, it uses our browser's time zone and displays the date as a full text string, such as "Fri Jun 17 2022 10:54:59 GMT+0100 (British Summer Time)" that contains the current date, time, and time zone.

What date format is dd mm yyyy in JavaScript?

To format a date as dd/mm/yyyy:Use the getDate() , getMonth() and getFullYear() methods to get the day, month and year of the date. Add a leading zero to the day and month digits if the value is less than 10 .

What is date now () format?

In this article, we will learn about the Date now() method in Javascript. The date. now() method is used to return the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC. Since now() is a static method of Date, it will always be used as Date.


2 Answers

You can build it manually:

var m = new Date();
var dateString = m.getUTCFullYear() +"/"+ (m.getUTCMonth()+1) +"/"+ m.getUTCDate() + " " + m.getUTCHours() + ":" + m.getUTCMinutes() + ":" + m.getUTCSeconds();

and to force two digits on the values that require it, you can use something like this:

("0000" + 5).slice(-2)

Which would look like this:

var m = new Date();
var dateString =
    m.getUTCFullYear() + "/" +
    ("0" + (m.getUTCMonth()+1)).slice(-2) + "/" +
    ("0" + m.getUTCDate()).slice(-2) + " " +
    ("0" + m.getUTCHours()).slice(-2) + ":" +
    ("0" + m.getUTCMinutes()).slice(-2) + ":" +
    ("0" + m.getUTCSeconds()).slice(-2);

console.log(dateString);
like image 79
Joseph Marikle Avatar answered Oct 12 '22 08:10

Joseph Marikle


No library, one line, properly padded

const str = (new Date()).toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");

It uses the built-in function Date.toISOString(), chops off the ms, replaces the hyphens with slashes, and replaces the T with a space to go from say '2019-01-05T09:01:07.123' to '2019/01/05 09:01:07'.

Local time instead of UTC

const now = new Date();
const offsetMs = now.getTimezoneOffset() * 60 * 1000;
const dateLocal = new Date(now.getTime() - offsetMs);
const str = dateLocal.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");
like image 50
MarredCheese Avatar answered Oct 12 '22 07:10

MarredCheese