0

I'm aware of packages like moment.js, but I would like to use only javascript. How can I get the current time as a string in Central US time?

I tried

let s = new Date().toLocaleString("en-US", { timeZone: "America/Chicago" });

But this returns the format as mm/dd/yyyy, hh:mm:ss which I detest.

I would like to get the year in front. Is that possible using toLocalString? I tried to change "en-US" to "iso" or "en-GB" but neither one will put the year in front.

John Henckel
  • 7,448
  • 2
  • 55
  • 68
  • 1
    You can use the [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) API to extract the various numbers from the Date instance and assemble them however you like, and adjust as necessary based on what `.getTimezoneOffset()` tells you about the actual local timezone. – Pointy Mar 17 '19 at 15:22
  • `getTimezoneOffset` is not useful. my server is running utc, so local time is irrelevant. What I want is to format the date string in Chicago time with the year in front. There does not seem to be any way to do that except (1) call `toLocalString` as above, and (2) parse the result string and reorder the substrings! Surely there is a better way? – John Henckel Mar 17 '19 at 16:46
  • Well if you're doing it server-side and you know your server's time setting then yes of course. However overall getting the "pieces" of a date (day, month, year, hour, minute, seconds, etc) is *really* easy via the Date API. – Pointy Mar 17 '19 at 16:53
  • let now = new Date(); let res = `${now.getFullYear()}-${now.getMonth()+1}-${now.getDate()} ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}` – Michael Hobbs Mar 17 '19 at 17:20
  • @Pointy Are the "pieces" in Chicago time or UTC? I need the pieces to be in Chicago time. – John Henckel Mar 17 '19 at 17:21
  • @MichaelHobbs the `getHours` is returning the wrong value. It always return local time but i need it to return Chicago time. – John Henckel Mar 17 '19 at 17:23
  • 2
    @JohnHenckel without a lib like Moment.js you will have to deal with DST on your own. let now = new Date(); let tz = -6 // or -5 let res = ${now.getFullYear()}-${now.getMonth()+1}-${now.getDate()} ${now.getHours() - tz}:${now.getMinutes()}:${now.getSeconds()} Maybe as Pointy suggest you can use .getTimezoneOffset(). I generally turn to Moment for any date/time issues as it can get ugly very quickly. – Michael Hobbs Mar 17 '19 at 18:32
  • 1
    The pieces of the date are in local time, so you should pre-adjust your UST date by the timezone offset you want (for Chicago time, 6 hours or 5 hours depending on whether you want DST). – Pointy Mar 17 '19 at 19:36

0 Answers0