2

I am able to get the output format that I need, but not the correct time. I need it in GMT (which is +4 hours)

var dt = new Date();
var dt2 = dt.toString('yyyyMMddhhmmss');

Any ideas? The output looks like:

20120403031408

I am able to get the GMT in standard string format by doing:

dt.toUTCString();

but im unable to convert it back to the yyyyMMddhhmmss string

EDIT: I am using the date.js library

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
user1309548
  • 25
  • 1
  • 4
  • What library or script are you using to get `toString(format)`? The [standard method](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/toString) doesn't acknowledge any arguments. – Jonathan Lonowski Apr 03 '12 at 19:27
  • Apologies, im using date.js. Edited the Question to reflect that. – user1309548 Apr 03 '12 at 19:41

2 Answers2

1

date.js's toString(format) doesn't have an option to specify "UTC" when formatting dates. The method itself (at the bottom of the file) never references any of Date's getUTC... methods, which would be necessary to support such an option.

You may consider using a different library, such as Steven Levithan's dateFormat. With it, you can either prefix the format with UTC:, or pass true after the format:

var utcFormatted = dateFormat(new Date(), 'UTC:yyyyMMddhhmmss');
var utcFormatted = dateFormat(new Date(), 'yyyyMMddhhmmss', true);

// also
var utcFormatted = new Date().format('yyyyMMddhhmmss', true);

You can also write your own function, as Dominic demonstrated.

Community
  • 1
  • 1
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
1

The key is to use the getUTC functions :

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

/* use a function for the exact format desired... */  
function ISODateString(d){  
  function pad(n) { return n < 10 ? '0'+n : n }
  return d.getUTCFullYear() + '-'  
       + pad(d.getUTCMonth() +1) + '-'  
       + pad(d.getUTCDate()) + 'T'  
       + pad(d.getUTCHours()) + ':'  
       + pad(d.getUTCMinutes()) + ':'  
       + pad(d.getUTCSeconds()) + 'Z'  
}  

var d = new Date();  
console.log(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z  
Dominic Goulet
  • 7,983
  • 7
  • 28
  • 56