8

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"
5
  • Why don't you want to include something which will make the issue you're having go away? Apr 11, 2017 at 9:25
  • 2
    Because loading a library for a couple of operations is overkill Apr 11, 2017 at 9:30
  • Depends on the amount of technical debt you're creating by trying to implement these "couple of methods". If you don't want a library, why not look inside an extract only what you want? Apr 11, 2017 at 9:32
  • There is no capacity within the built-in Date object methods to do what you're asking. You'll end up writing something that is pretty much the same as current libraries that do the same thing. The ECMA-402 Internationalisation API is implementation dependent so while you can specify the parts and language, you can't precisely specify the format. Also, it specifies languages, not locations, even though the language argument is called, incorrectly, "locale".
    – RobG
    Apr 11, 2017 at 20:58
  • Just the data component of the IANA timezone database, which contains the timezone information you need, is 205kb.
    – RobG
    Apr 11, 2017 at 21:05

4 Answers 4

13
const dt = new Date().toLocaleString("sv-SE");
3
  • 4
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: stackoverflow.com/help/how-to-answer . Good luck 🙂
    – nima
    Oct 7, 2021 at 9:29
  • 1
    It looks like there isn't a locale for ISO standards, so the next best thing is to use a locale for a place that uses ISO standards for time. This one is Sweden. Jun 22, 2022 at 4:21
  • 1
    Also new Date().toLocaleString("lt") works. This one is Lithuanian Jan 3 at 20:35
3

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.

3
  • But not all browsers that have implemented ECMA-402 have also implemented the timezone option for values other than UTC. For the above, Firefox 38 returns "RangeError: invalid time zone". Also, for the above, IE 10's toLocaleString returns a string in format "DDDD, d MMMM YYYY h:mm:ss A" (using moment.js tokens) so the reformatting won't work either. :-(
    – RobG
    Apr 12, 2017 at 6:05
  • 1
    This nice but missing the zero padding for the date
    – EliSherer
    Jan 3, 2019 at 8:36
  • Padding should already be there in the output from toLocaleString Jan 3, 2019 at 15:29
1

Something like this might be what you need: First format the timestamp as you wish, including timezone offset and then change the position of the numeric items as you need it, usign the replace function with regex:

const timeStamp = new Date().toLocaleString('de-DE', {
                    timeZone: 'Europe/Berlin',
                    hour12: false,
                    year: "numeric",
                    month: "2-digit",
                    day: "2-digit",
                    hour: "2-digit",
                    minute: "2-digit",
                    second: "2-digit",
                }).replace(/(\d+)\.(\d+)\.(\d+),\s(\d+):(\d+):(\d+)/, "$3$2$1_$4$5$6");
3
  • 2
    Beware -- not all environments will support the locale you are using such as in this case de-DE. That'll mean toLocaleString doesn't output the format you were expecting, and so the regex replacement won't work.
    – tremby
    Nov 10, 2020 at 21:47
  • You're right. Changing the locale will require to change the regex too.
    – Iulian M.
    Dec 11, 2020 at 8:22
  • My point was more that this cannot be relied on even if you do have the right regex for the locale you've specified. As soon as one visitor does not have that same locale available, the code will not be functioning properly.
    – tremby
    Dec 11, 2020 at 9:26
0

You can't do what you're asking using built-in methods as ECMAScript implementations aren't required to store historical data for all (or even any) time zones. They are only required to have access to the current time zone offset of the host.

Also, the ECMA-402 Internationalisation API isn't sufficient either. While it allows the timezone to be specified, not all implementations support ECMA-402 and of those that do, not all support time zones values other than "UTC" (which is the only one ECMA-402 requires support for, others are optional). And it's very difficult to impossible to exactly specify the format using only ECMA-402.

I think you're much better off to use an existing library like moment.js with Moment-timezone.js. The download isn't that big relative to the general size of web pages (which seem to be 1MB at least lately). If you try to write something yourself you'll just end up with something very moment-like anyway.

To reduce the size of the download, you can get just the time zone data for 2012 to 2022.

If you want to use your simplified call, then a small magicDateFormatter can leverage the moment.js stuff:

/* Return date string for a date in the required timezone and format
** @param {string} timezone: IANA time zone designator, e.g. Asia/Sakhalin
** @param {Date}   [date]  : date to use, default is current date
** @param {string} [format]: output format using Moment.js tokens, 
**                         default is 'YYYY-MM-DDTHH:mm:ssZZ'
** @returns {string}       : formatted string
**
** magicDateFormatter(timezone[, date[, format]])
*/
function magicDateFormatter(timezone, date, format) {
  // Validate that the time zone is supported
  if (!moment.tz.zone(timezone)) {
    return 'Unknown time zone: "' + timezone + '"';
  }
  // Use current date if not supplied
  date = date || new Date();
  // Use default format if not supplied
  format = format || 'YYYY-MM-DDTHH:mm:ssZZ'
  return moment(date).tz(timezone).format(format)
}

console.log(magicDateFormatter('Europe/Paris'));
console.log(magicDateFormatter('Asia/Sakhalin', new Date(2016,1,29), 'Do MMMM, YYYY'));
console.log(magicDateFormatter('foo/bar'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data.min.js"></script>

Of course you could also specify the format in the call if you want.

2
  • 1
    ECMA-402 does indeed have time zone support, and most newish browsers can use it now. Apr 12, 2017 at 1:33
  • @MattJohnson—good to know, but ECMA-402 is still UTC with the option of support for other timezones. Firefox 38 supports ECMA-402 but ignores the timezone option other than "UTC". Also still not practical to exactly specify the format.
    – RobG
    Apr 12, 2017 at 5:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.