Alan Yong
Alan Yong

Reputation: 1033

Convert datetime with time zone to specific format with it's timzone

Convert

2020-11-15T02:20:00+03:00

To

15-11-2020 2:20 (+3:00) (any format will do, as long the showing the timezone)

moment or pure javascript (strictly no jquery)

Update:

+3:00 is dynamic value. Could be +4:00 or +5:00.

Upvotes: 0

Views: 70

Answers (1)

Ihor Vyspiansky
Ihor Vyspiansky

Reputation: 916

If your date format has a fixed timezone offset, try to use moment.parseZone.

const dateString = '2020-11-15T02:20:00+03:00';
const momentDate = moment.parseZone(dateString);

console.log(momentDate.format('DD-MM-YYYY h:mm (Z)'));
// Output: "15-11-2020 2:20 (+03:00)"

Update:

Use H instead of h:

const momentDate = moment.parseZone('2020-11-15T23:23:00+03:00');

console.log(momentDate.format('DD-MM-YYYY h:mm (Z)'));
// Wrong hour: "15-11-2020 11:23 (+03:00)"

console.log(momentDate.format('DD-MM-YYYY H:mm (Z)'));
// Correct output: "15-11-2020 23:23 (+03:00)"

Thanks to @MattJohnson-Pint for correcting the format template.

Demo - https://codepen.io/vyspiansky/pen/OJNRbPN

Upvotes: 3

Related Questions