I have tried to create a time converter, which converts an upcoming time (for example 2:00pm EDT) to another time zone (for example UTC). The upcoming time is stored in a string at first, and gets converted into a date (I'm not very good at using Dates) (let date = Date.parse(time + ', ' timezone)
), but it gives either Invalid Date
or NAN
.
If someone knows how to convert a string containing the time into another timezone, please share it in the comments.
Asked
Active
Viewed 297 times
0
-
Please provide enough code so others can better understand or reproduce the problem. – Community Aug 05 '22 at 14:21
-
`Date.parse(time + ', ' timezone)` is seriously misguided, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Aug 06 '22 at 10:42
2 Answers
0
It's best to use a dedicated Date/Time library, such as luxon
for this type of conversion.
We create a DateTime object in the desired timezone, in this case 'America/New_York' (this is more precise that the abbreviation EDT which is ambiguous).
The date can be converted to UTC using DateTime.toUTC();
const{ DateTime } = luxon;
const dt = DateTime.fromObject( { year: 2022, month: 8, day: 5, hour: 14 }, { zone: 'America/New_York'} )
console.log('Time (in zone):', dt.toString());
console.log('Time (UTC): ', dt.toUTC().toString());
.as-console-wrapper { max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.0.1/luxon.min.js" integrity="sha512-6ZJuab/UnRq1muTChgrVxJhSgygmL2GMLVmSJN7pcBEqJ1dWPbqN9CiZ6U3HrcApTIJsLnMgXYBYgtVkJ8fWiw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Terry Lennox
- 29,471
- 5
- 28
- 40
-1
You just have to use .toISOString()
method.
new Date(time).toISOString()
it will automatically convert to UTC

owenizedd
- 1,187
- 8
- 17
-
How does this **reliably** parse a timestamp in one timezone and produce a timestamp for a different timezone? Why does the OP get *Invalid Date* or *NAN*? How does your code address that? – RobG Aug 06 '22 at 10:46