Reputation: 1180
I am getting this "2019-05-05T10:30:00Z"
type of time from an API. But I need to convert it like this "10:30 AM (3:30 PM Your Time)"
. I am using reactJs for my client side. How can I convert the time as user current timezone?
Upvotes: 3
Views: 11623
Reputation: 2704
const dateToTime = date => date.toLocaleString('en-US', {
hour: 'numeric',
minute: 'numeric'
});
const dateString = "2019-05-05T10:30:00Z";
const userOffset = new Date().getTimezoneOffset()*60*1000;
const localDate = new Date(dateString);
const utcDate = new Date(localDate.getTime() + userOffset);
console.log(`${dateToTime(utcDate)} (${dateToTime(localDate)} Your Time)`);
Upvotes: 6
Reputation: 642
take a look at momentjs. it has localization and you can do also custom things.
Upvotes: 2
Reputation: 512
Your API send server DateTime in response, you can just use below function that can convert to your local time zone.
function convertUTCDateToLocalDate(date) {
var dateLocal = new Date(date);
var newDate = new Date(dateLocal.getTime() - dateLocal.getTimezoneOffset()*60*1000);
return newDate;
}
Upvotes: 1