'Javascript date format like ISO but local
how do I format a javascript date like ISO format, but in local time?
with myDate.toISOString() I am getting the time as: "2012-09-13T19:12:23.826Z"
but here, it is 22:13, so how do I include the timezone in above format?
I ended up doing...
pad=function(e,t,n){n=n||"0",t=t||2;while((""+e).length<t)e=n+e;return e}
c = new Date()
c.getFullYear()+"-"+pad(c.getMonth()+1)+"-"+pad(c.getDate()-5)+"T"+c.toLocaleTimeString().replace(/\D/g,':')+"."+pad(c.getMilliseconds(),3)
Solution 1:[1]
No library required! For some Date object, e.g. t = new Date()
convert the local time zone offset from minutes to milliseconds
z = t.getTimezoneOffset() * 60 * 1000subtract the offset from t
tLocal = t-zcreate shifted Date object
tLocal = new Date(tLocal)convert to ISO format string
iso = tLocal.toISOString()drop the milliseconds and zone
iso = iso.slice(0, 19)replace the ugly 'T' with a space
iso = iso.replace('T', ' ')
Result is a nice ISO-ish format date-time string like "2018-08-01 22:45:50" in the local time zone.
Solution 2:[2]
A bit of a hack but can be done in one line by taking advantage of the fact that Sweden uses a format very close to ISO:
// Returns a string like 2021-01-17T01:59:57
function dateToISOButLocal(date) {
return date.toLocaleString('sv').replace(' ', 'T');
}
Solution 3:[3]
I went with what Denis Howe said, below as a ready made function for convenience.
Also one fix: in the original answer t-z does not work because t is a Date, not milliseconds.
function dateToISOLikeButLocal(date) {
const offsetMs = date.getTimezoneOffset() * 60 * 1000;
const msLocal = date.getTime() - offsetMs;
const dateLocal = new Date(msLocal);
const iso = dateLocal.toISOString();
const isoLocal = iso.slice(0, 19);
return isoLocal;
}
With this I get the kind of string that needed as a URL parameter:
"2018-11-16T12:23:50"
Solution 4:[4]
Although answers here might work, there's nothing like a simple one-liner:
new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60 * 1000).toISOString()
Explanation for those who are interested:
We create a new instance of Date (the outer one).
We give it another instance of Date (in milliseconds) from which we subtract the timezone offset (in milliseconds too, either positive or negative). All of this we format into ISO
Solution 5:[5]
I don't quite understand which date did you need but I think you need
const ISOLocaleString = d => {
const pad = n => n < 10 ? '0'+n : n;
return d.getFullYear()+'-'
+ pad(d.getMonth()+1)+'-'
+ pad(d.getDate())+'T'
+ pad(d.getHours())+':'
+ pad(d.getMinutes())+':'
+ pad(d.getSeconds())+'Z'
}
or
const ISOUTCLocaleString = d => {
const pad = n => 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'
}
Solution 6:[6]
In the original post, the current ISO date is "2012-09-13T19:12:23.826Z"
If what is wanted is a date that respects ISO norm but reflects the local offset from UTC time, the target answer should be "2012-09-13T22:12:23.826+03:00".
Best answer in the post bellow, with code snippet that respects the ISO 8601 format / RFC 3339
Solution 7:[7]
Another method is to define a prototype on the Date object that leverages the built-in toISOString method (a separate function is also provided):
// Extend Date.prototype
Date.prototype.toLocalISOString = function() {
// Get the local offset for the date in minutes
let offsetMins = this.getTimezoneOffset();
// Get a time value adjusted for the offset
let localTimeMs = this - offsetMins * 6e4;
// Make a new Date so don't affect this
let date = new Date(localTimeMs);
// Get the local offset sign (ECMAScript sign is opposite to usual)
let utcOffsetSign = offsetMins > 0? '-' : '+';
// Remove sign from offsetMins
offsetMins = Math.abs(offsetMins);
// Get offset hours and minutes, padd to 2 digits
let utcOffsetHr = String(offsetMins / 60 | 0).padStart(2,'0');
let utcOffsetMin = String(offsetMins % 60).padStart(2,'0');
// Build offset string
let utcOffsetString = `${utcOffsetSign}${utcOffsetHr}:${utcOffsetMin}`;
// Return as adjusted ISO 8601 format string with adjusted offset
return date.toISOString().replace('Z', utcOffsetString);
};
// E.g.
let date = new Date();
// Like 2020-08-04T14:52:38.613-07:00
console.log(`UTC : ${date.toISOString()}\n` +
`Local: ${date.toLocalISOString()}`);
// Stand alone function
function toISOLocal(date) {
let offsetMins = date.getTimezoneOffset();
let d = new Date(date - offsetMins*6e4);
let offsetSign = offsetMins > 0? '-' : '+';
offsetMins = Math.abs(offsetMins);
let offsetHr = String(offsetMins / 60 | 0).padStart(2,'0');
let offsetMin = String(offsetMins % 60).padStart(2,'0');
return d.toISOString().replace('Z', `${offsetSign}${offsetHr}:${offsetMin}`);
}
// Like 2020-08-04T14:52:38.613-07:00
console.log(`fn : ${toISOLocal(date)}`);
Solution 8:[8]
There's no direct way to do this. However, you can use toLocaleString to create a string that you can easily parse to make it an ISO string.
This works on node:
function getLocalIsoTime(time, timezone) {
const local = time.toLocaleString("en-US", {timeZone: timezone, hour12: false, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit"});
return `${local.substr(6, 4)}-${local.substr(0, 2)}-${local.substr(3, 2)}T${local.substr(12, 8)}`;
}
console.log(getLocalIsoTime(new Date(), 'Asia/Kolkata'));
A simpler version works on node 15+ and on most modern browsers:
function getLocalIsoTime(time, timezone) {
return time.toLocaleString("en-CA", {timeZone: timezone, hour12: false}).replace(/, /, "T");
}
console.log(getLocalIsoTime(new Date(), 'Asia/Kolkata'));
Solution 9:[9]
ISO 8601 is simply a way of formatting dates and can as such can be applied to any time zone.
Have you tried the timeZone option to the Date object's toLocaleString method?
This question has answers with examples.
Solution 10:[10]
This is the method I use. It takes care to add zeros if date/month/hour etc is single digit number (for example turns '6' to '06')
function formatLikeISO (d: Date): string {
let lengthChecker = (str) => {
if (str.length == 1) { return '0' + str; }
return str;
}
let theDate = lengthChecker(String(d.getDate()));
let month = lengthChecker(String(d.getMonth() + 1));
let mins = lengthChecker(String(d.getMinutes()));
let hours = lengthChecker(String(d.getHours()));
let secs = lengthChecker(String(d.getSeconds()));
let formatted =
d.getFullYear() + '-' +
month + '-' +
theDate + ' ' +
hours + ':' +
mins + ':' +
secs;
return formatted;
}
This will output this kind of format:
"2021-06-30 11:31:34"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
