admin管理员组

文章数量:1287137

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?

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?

Share Improve this question asked May 23, 2019 at 18:24 Sunny SultanSunny Sultan 1,1801 gold badge16 silver badges22 bronze badges 1
  • 2 Possible duplicate of Display date/time in user's locale format and time offset – AlexMA Commented May 23, 2019 at 18:31
Add a ment  | 

3 Answers 3

Reset to default 6

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)`);

take a look at momentjs. it has localization and you can do also custom things.

https://momentjs.

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;
}

本文标签: reactjsHow to convert a time to user local timezone in javascriptStack Overflow