Here is a standard way to serialise date as ISO 8601 string in JavaScript:
var now = new Date(); console.log( now.toISOString() ); // outputs '2015-12-02T21:45:22.279Z'
I need just the same output, but without milliseconds. How can I output 2015-12-02T21:45:22Z
?
To remove the T and Z characters from an ISO date in JavaScript, we first need to have the date in ISO format. If you don't have it already, you can convert it to ISO using the toISOString function on a Date object. This will get rid of both T and Z, resulting in "2022-06-22 07:54:52.657".
ISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).
Z is the zone designator for the zero UTC offset. "09:30 UTC" is therefore represented as "09:30Z" or "T0930Z". "14:45:15 UTC" would be "14:45:15Z" or "T144515Z". The Z suffix in the ISO 8601 time representation is sometimes referred to as "Zulu time" because the same letter is used to designate the Zulu time zone.
Date formatting On the contrary to the time zone, by default the number of milliseconds is not displayed. However, when displayed, the format is: "yyyy-MM-dd'T'hh:mm:ss. sss'Z'" if in UTC or "yyyy-MM-dd'T'hh:mm:ss. sss[+|-]hh:mm" otherwise.
Simple way:
console.log( new Date().toISOString().split('.')[0]+"Z" );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With