0

I want to construct a Date object along with dynamically selected timezone. I am currently in IST time zone. I want to eliminate the usage of Date.parse() as it does not behave as expected at times. let's assume tzOffset to be +05:30 for now. It could be any other timezone based on what users want. new Date(epochDate).toISOString(); converts the date to UTC timezone. How do I get the date in toISOString() format but also get it in the desired time zone

const tsConstruct = `${year}-${month}-${date}T${hour}:${min}:00${tzOffset}`;
      const epochDate = Date.parse(tsConstruct);
      scheduledTs = new Date(epochDate).toISOString();
MelDsz
  • 179
  • 4
  • 14
  • 1
    Have a look at [momentjs](https://momentjs.com/) – Ru Chern Chong Apr 04 '18 at 09:36
  • Any javascript method to achieve this? @RuChernChong – MelDsz Apr 04 '18 at 09:38
  • 1
    Date objects are always UTC. The timezone offset is from the host, it's not a property of the Date. The offset is used when creating a Date to ensure the time value is UTC. It is also used to generate "local" (host system) date and time values from the internal UTC time value. If you want a string in a particular format, you can do that yourself or use a formatting library, there are plenty to chose from. See [*Where can I find documentation on formatting a date in JavaScript?*](https://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – RobG Apr 04 '18 at 12:13

1 Answers1

1

JavaScript's Date does not store timezone info. It just stores the number of milliseconds from UNIX EPOCH. Then, depending if you use the UTC methods or not, it returns the date and time in UTC or the local time.

You should have to change the date and time, based on the timezone indicated, to UTC or local time, and then store it in a Date object. But, of course, to show the stored time in another timezone different to the local one or UTC, you must do the conversions yourself, so, as @RuChengChong suggested, use a helper library like momentjs.

Oscar Paz
  • 18,084
  • 3
  • 27
  • 42
  • I tried `moment(epochDate).utcOffset(tzOffset)` here `tzOffset` is a string say, +05:30. this isn't working. How can I get the date in a timezone other than UTC – MelDsz Apr 05 '18 at 03:11
  • Unfortunately, I've never used `momentjs` myself, so I can't help you with it. – Oscar Paz Apr 05 '18 at 10:04