sarsnake sarsnake - 2 months ago 18
Javascript Question

Javascript Date output formatting

I need to capture the Now() date and time in the YYYY/mm/dd hh:m:sec format. It needs to be in GMT time.

How do I achieve that with Javascript?

Answer

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);
Comments