I've been using MomentJS a lot but I'm starting a new project and I don't want to include this library since I play with dates only a couple of times.
So what I'm trying to do is to get the string representation of a date, in ISO-like format ('YYYY-MM-DDZHH:mm:ss' or 'YYYY-MM-DD HH:mm:ss'). I don't want it in UTC: I want it in a given timezone (that I can provide programatically).
E.g the representation for right now would be "2017-04-11 11:20:00" (French timezone - eq to "2017-04-11 09:22:00Z".)
I want native Javascript. I've been playing with toLocaleString with no success.
Thanks
[edit] In a perfect world, I'm looking for a function that takes a date format, a timezone, and return the string I want. Like:
function magicDateFormatter(format, tz) {
/* ... */
}
var now = new Date();
console.log(magicDateFormatter('YYYY-MM-DD HH:mm:ss', 'Europe/Paris'));
// print "2017-04-11 11:20:00"
const dt = new Date().toLocaleString("sv-SE");
Something like this might work for you:
function formatDateWithZone(date, tz) {
var s = date.toLocaleString('en-GB', { timeZone: tz });
var a = s.split(/\D/);
return a[2] + '-' + a[1] + '-' + a[0] + ' ' + a[4] + ':' + a[5] + ':' + a[6];
}
Usage:
formatDateWithZone(new Date(), 'Europe/Paris') // "2017-04-12 03:37:59"
This will work in environments that have implemented time zone support via ECMA-402. The compatibility table here will show you which support them, by expanding the DateTimeFormat section, and looking at the row labeled accepts IANA timezone names.
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