I have an ISO8601 formatted datetime 2024-12-26T22:22:00+12:00
and I want to be able to format the datetime in both original timezone, in this case 22:22
, and user timezones (I.e. 04:22
for CST)
I am looking for idiomatic way of showing the original time using JS Library (dayjs
, date-fns
or luxon
)
// Browser timezone (e.g. CST-06:00)
const dateStr = "2024-12-26T22:22:00+12:00";
It’s easy to display date in browser time:
// date-fns
format(parseISO(dateStr), "HH:mm"); // 04:22
// dayjs
dayjs(dateStr).format("HH:mm"); // 04:22
But how I can format time at the original offset?
I was able to do this using moment
and js-joda
, but not date-fns
, dayjs
or luxon
:
dayjs.extend(dayjs_plugin_utc);
dayjs.extend(dayjs_plugin_timezone);
const isoString = '2024-12-26T22:22:00+12:00';
document.getElementById('iso').textContent = isoString;
const updateTime = (id, value) => {
document.getElementById(id).textContent = value;
};
// date-fns
const { format, parseISO } = window.dateFns;
updateTime('fns', format(parseISO(isoString), 'HH:mm '));
updateTime('fns-original', "?");
// dayjs
updateTime('dayjs', dayjs(isoString).local().format('HH:mm'));
updateTime('dayjs-original', "?");
// luxon
const { DateTime } = window.luxon;
updateTime('luxon', DateTime.fromISO(isoString).toFormat('HH:mm'));
updateTime('luxon-original', "?");
// moment
updateTime('moment', moment(isoString).format('HH:mm'));
updateTime('moment-original', moment.parseZone(isoString).format('HH:mm'));
// js-joda
const { ZonedDateTime, ZoneId, DateTimeFormatter } = JSJoda;
updateTime('joda', ZonedDateTime.parse(isoString).withZoneSameInstant(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern('HH:mm')));
updateTime('joda-original', ZonedDateTime.parse(isoString).format(DateTimeFormatter.ofPattern('HH:mm')));
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Time Comparison</title>
<script src="https://cdn.jsdelivr.net/npm/date-fns@latest"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@latest"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs/plugin/timezone.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs/plugin/utc.js"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@latest"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@latest"></script>
<script src="https://cdn.jsdelivr.net/npm/js-joda@latest"></script>
</head>
<body>
<h3>ISO String: <span id="iso"></span></h3>
<h4>Local Time</h4>
<p>date-fns: <span id="fns"></span></p>
<p>dayjs: <span id="dayjs"></span></p>
<p>luxon: <span id="luxon"></span></p>
<p>moment: <span id="moment"></span></p>
<p>js-joda: <span id="joda"></span></p>
<h4>Original Time</h4>
<p>date-fns: <span id="fns-original"></span></p>
<p>dayjs: <span id="dayjs-original"></span></p>
<p>luxon: <span id="luxon-original"></span></p>
<p>moment: <span id="moment-original"></span></p>
<p>js-joda: <span id="joda-original"></span></p>
</body>
</html>
2