Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript dates: toGMTString, but also ISO 8601 format?

Is there an easy way to convert a date object to GMT time, but also display in ISO 8601 format?

like image 984
Upperstage Avatar asked Dec 03 '25 16:12

Upperstage


2 Answers

Is there an easy way to convert a date object to GMT time

Yes:

var d = new Date();
d.toGMTString()

but also display in ISO 8601 format?

Function taken form here (they also have an ISO 8601 parser there)

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'
}
like image 135
Tomalak Avatar answered Dec 05 '25 04:12

Tomalak


The best solution I've come across is to use the Moment.js javascript library and use the following code:

To get the current ISO time with timezone information and milliseconds

now = moment().format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
// "2013-03-08T20:11:11.234+0100"

now = moment().utc().format("YYYY-MM-DDTHH:mm:ss") + "Z"
// "2013-03-08T19:11:11Z" <- better use the native .toISOString() 

To get the ISO time of a native JavaScript Date object with timezone information but without milliseconds

var current_time = Date.now();
moment(current_time).format("YYYY-MM-DDTHH:mm:ssZZ")
like image 44
Daniel F Avatar answered Dec 05 '25 05:12

Daniel F



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!