0

I am trying to convert a datetime string to JS date obj. My Input is 2021-09-16 19:15:52.930. The problem is this string doesn't have a timezone, And I need to mark them in cdt/cst(depending on daylight savings) timezone when converting to JS date obj.

The way I am trying to do is:

let dt = new Date('2021-09-16 19:15:52.930 Timezone')

I could pass CDT or CST in placeof timezone, to get it parsed. But in this case, my logic needs to know which timezone is currently being followed depending on time in year. I wanted a way so that it can be handled automatically by JS, Like- passing CT? 2021-09-16 19:15:52.930 CT But this doesn't seem to be supported by Date().

Nandan Raj
  • 105
  • 3
  • 13
  • So if your date string has no timezone, what do you assume as the timezone? UTC? As long as you have no timezone with a date this date would be different on different places of the world. Is that what you want to achieve? – Thallius Sep 24 '21 at 07:40
  • Probably a duplicate of [*How to initialize a JavaScript Date to a particular time zone*](https://stackoverflow.com/questions/15141762/how-to-initialize-a-javascript-date-to-a-particular-time-zone) – RobG Sep 24 '21 at 08:36
  • @ClausBönnhoff Date string is coming from America/Mexico_City and is in CDT/CST timezone. My end goal is to Convert this string(appending timezone info) to JS date obj, And later get UTC time from this JS object – Nandan Raj Sep 24 '21 at 09:19
  • Seems you want to add a location parameter to parse the timestamp, like `let date = new Date('2021-09-16T19:15:52.930', 'America/Mexico_City')` so that the timestamp is parsed with whatever offset applied to the location on that date and time. That will be possible with the proposed [*Temporal* object](https://tc39.es/proposal-temporal/docs/cookbook.html?futuredate=2021-09-16), but for now requires a library or for you to write your own function ([not a trivial task](https://stackoverflow.com/questions/61361914/calculate-timezone-offset-only-for-one-particular-timezone/61364310#61364310)). – RobG Sep 24 '21 at 09:52
  • @RobG thanks for the help, Used luxon library to solve this issue. – Nandan Raj Sep 24 '21 at 17:57

1 Answers1

0

If you don't pass anything and use it like this,

new Date('2021-09-16 19:15:52.930')

JS will consider it as your machine's timezone.

If you want it as UTC, add the letter Z like this,

new Date('2021-09-16 19:15:52.930Z')

If you want a specific timezone, add the time difference from UTC. For CDT it is -5:00,

new Date('2021-09-16 19:15:52.930-05:00')
Antajo Paulson
  • 555
  • 1
  • 4
  • 15
  • `new Date('2021-09-16 19:15:52.930')` returns an invalid date in some implementations, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Sep 24 '21 at 20:34