Get GMT String from current Date

你离开我真会死。 提交于 2019-12-02 01:58:28
Jonathan Lonowski

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.

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  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!