Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the current datetime in the format "2014-04-01:08:00:00" in Node?

Tags:

date

node.js

I need the current system datetime in the format "yyyy-mm-dd:hh:mm:ss".

https://stackoverflow.com/a/19079030/2663388 helped a lot.

new Date().toJSON() is showing "2014-07-14T13:41:23.521Z"

Can someone help me to extract "yyyy-mm-dd:hh:mm:ss" from "2014-07-14T13:41:23.521Z"?

like image 928
anand Avatar asked Jul 14 '14 13:07

anand


2 Answers

Though other answers are helpful I found the following code is working for me.

var d = new Date();
console.log(d.toJSON().slice(0,19).replace('T',':'));

The output on console is: 2014-07-15:06:10:16. I am using Node.js Express on Ubuntu.

like image 148
anand Avatar answered Oct 03 '22 01:10

anand


Cleaner version of @Bernhard code using padStart and without deprecated getYear

function getCurrentDateTimeString() {
    const date = new Date();
    return date.getFullYear() + '-' +
        (date.getMonth() + 1).toString().padStart(2, '0') + '-' +
        date.getDate().toString().padStart(2, '0') + ':' +
        date.getHours().toString().padStart(2, '0') + ':' +
        date.getMinutes().toString().padStart(2, '0') + ':' +
        date.getSeconds().toString().padStart(2, '0');
}

console.log(getCurrentDateTimeString());
like image 24
Alex P. Avatar answered Oct 03 '22 01:10

Alex P.