Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

Using NodeJS, I want to format a Date into the following string format:

var ts_hms = new Date(UTC); ts_hms.format("%Y-%m-%d %H:%M:%S"); 

How do I do that?

like image 322
Tampa Avatar asked May 18 '12 02:05

Tampa


People also ask

How do I get current UTC time in node JS?

Use the toUTCString() method to get the current date and time in utc, e.g. new Date(). toUTCString() .

How do you format a Date in a type script?

You can format date/time in TypeScript, by using any of the built-in methods on the Date object or creating a reusable function that formats the date according to your requirements by leveraging built-in methods like getFullYear , getMonth , etc.

How can get current Date in YYYY-MM-DD format in jquery?

You can do it like that: var d = new Date(); var month = d. getMonth()+1; var day = d. getDate(); var output = d.


1 Answers

If you're using Node.js, you're sure to have EcmaScript 5, and so Date has a toISOString method. You're asking for a slight modification of ISO8601:

new Date().toISOString() > '2012-11-04T14:51:06.157Z' 

So just cut a few things out, and you're set:

new Date().toISOString().   replace(/T/, ' ').      // replace T with a space   replace(/\..+/, '')     // delete the dot and everything after > '2012-11-04 14:55:45' 

Or, in one line: new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')

ISO8601 is necessarily UTC (also indicated by the trailing Z on the first result), so you get UTC by default (always a good thing).

like image 122
chbrown Avatar answered Oct 10 '22 10:10

chbrown