I'm trying to convert the time ( time alone ) from a known timezone to my local timezone with Moment.js.
I wrote the following function and, I am getting invalidDate
as the output.
const convertToLocalTime = (time, tz) => {
const t = moment.tz(time, tz)
const localTime = t.local()
}
time
is just time; without any date eg: 10:06 am
and, tz
is a timezone string for eg: Europe/Berlin
What am I doing wrong?
See Parsing in Zone:
The
moment.tz
constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.
Since your input (10:06 am
) is not in ISO 8601/RFC 2822 recognized format (see moment(String)
docs), you have to pass format parameter as shown in moment(String, String)
.
Here a live sample:
const convertToLocalTime = (time, tz) => {
const t = moment.tz(time, 'hh:mm a', tz)
const localTime = t.local()
return localTime;
}
const res = convertToLocalTime("10:06 am", 'Europe/Berlin');
console.log( res.format('hh:mm a') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data-2012-2022.min.js"></script>