Right now i am using this function
const setDuration = () => {
const currentDate = new Date();
const newDate = new Date(currentDate.getTime());
const year = newDate.getUTCFullYear();
const month = String(newDate.getUTCMonth() + 1).padStart(2, '0');
const day = String(newDate.getUTCDate()).padStart(2, '0');
const hours = String(newDate.getUTCHours()).padStart(2, '0');
const minutes = String(newDate.getUTCMinutes()).padStart(2, '0');
const seconds = String(newDate.getUTCSeconds()).padStart(2, '0');
const milliseconds = String(newDate.getUTCMilliseconds()).padEnd(7, '0');
const timeZoneOffset = newDate.getTimezoneOffset();
const timeZoneOffsetHours = Math.abs(Math.floor(timeZoneOffset / 60));
const timeZoneOffsetMinutes = Math.abs(timeZoneOffset % 60);
const timeZoneOffsetSign = timeZoneOffset < 0 ? '-' : '+';
return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}${timeZoneOffsetSign}${String(timeZoneOffsetHours).padStart(2, '0')}:${String(timeZoneOffsetMinutes).padStart(2, '0')}`;
}
I am Expecting this format => 2023-09-14T10:12:03.7380000+00:00
3
Answers
Yes, in JavaScript you can format a date into ISO 8601 format using the toISOString method available on Date objects.
For your specific use you could use it like this:
Is it 2023, every language has refactored its date API (see java evolution from Date, to Calendar, to Instant/DateTime), or wants to.
Also it seems you want nanosecond (micro?), bu JS do not offer such possibility without the use of libraries. (you did not specify if browser or node runtime)
It is js, so there are plentiful of large use libraries. So the case of not using libraries because you do not want to is wrong.
Why not use a library (luxon, momen) that is tested to work in plenty of scenarios ? (like yours)
I think this will solve your query