Reputation: 455
I have problem retriving data from an api and display it in local time.
API print to me zulu datetime 2021-11-12T14:30:29.000000Z
I've tried varius soluton to transform it to Europe/Rome gtm but anyone worked, considering olso DST..
moment(d.acktime, "YYYYMMDDHHmmss").utcOffset('Europe/Rome').format("HH:mm");
moment(d.acktime, "YYYYMMDDHHmmss").tz("Europe/Rome").format("HH:mm");
The data displayed is always the zulu tume coming form api.. any ideas??
Upvotes: 0
Views: 756
Reputation: 48713
Moment will parse an ISO 8601 without specifying a format:
When creating a moment from a string, we first check if the string matches known ISO 8601 formats, we then check if the string matches the RFC 2822 Date time format before dropping to the fall back of
new Date(string)
if a known format is not found.
Just make sure you use the moment-timezone (with data) library.
const d = { acktime: '2021-11-12T14:30:29.000000Z' };
const formatted = moment(d.acktime).tz('Europe/Rome').format('HH:mm');
console.log(formatted); // 15:30 (Rome is GMT+1)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.34/moment-timezone-with-data.min.js"></script>
Moment is EOL, so I recommend Luxon as an alternative. It is created by the same developers. Setting the timezone is also easier and does not require additional plugins and libraries. See "Time zones and offsets" for more information.
const { DateTime } = luxon;
const d = { acktime: '2021-11-12T14:30:29.000000Z' };
const formatted = DateTime.fromISO(d.acktime).setZone('Europe/Rome').toFormat('HH:mm');
console.log(formatted); // 15:30 (Rome is GMT+1)
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.1.1/luxon.min.js"></script>
Upvotes: 1