简体   繁体   中英

Get timestamp from date string without timezone and timezone name apart

I have a dateTime string in this (bad, I know) format coming from an external API:

const startDate = '2/13/2020 15:00';

and the timezone name:

const timezoneName = 'America/New_York';

Which means that the dateTime is 2/13/2020 15:00 in New York .

Any idea for an elegant way to get timestamp (or JavaScript date object)?

I don't mind using moment.js or/and moment-timezone if it helps.

Using moment-timezone should work:

const moment = require('moment-timezone');
const t = moment.tz("2/13/2020 15:00", "MM/DD/YYYY HH:mm","America/New_York");
console.log(t.toISOString()); // Prints '2020-02-13T20:00:00.000Z'

Moment and Moment-Timezone are for legacy code.

For new applications, the Moment team recommends Luxon .

const startDate = '2/13/2020 15:00';
const timezoneName = 'America/New_York';

const dateTime = luxon.DateTime.fromFormat(startDate, 'M/d/yyyy HH:mm',
                                           { zone: timezoneName });
const utcDateTime = dateTime.toUTC();
const s = utcDateTime.toISO();

console.log(s); //=> "2020-02-13T20:00:00.000Z"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM