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?
Asked
Active
Viewed 9,301 times
4

Sunny Sultan
- 1,090
- 15
- 20
-
2Possible duplicate of [Display date/time in user's locale format and time offset](https://stackoverflow.com/questions/85116/display-date-time-in-users-locale-format-and-time-offset) – AlexMA May 23 '19 at 18:31
4 Answers
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)`);

Matteo Basso
- 2,694
- 2
- 14
- 21
2
take a look at momentjs. it has localization and you can do also custom things.

mrTurkay
- 642
- 1
- 7
- 13
-
2
-
1this is just a library, also I like it, I use it almost all of my projects. so I recommend it, what is wrong with it? – mrTurkay May 23 '19 at 19:16
-
2Unfortunately, Moment's own website recommends against using it as of 2020. – Terry Jan 09 '22 at 04:53
1
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;
}

Archin Modi
- 492
- 1
- 8
- 19
-1
I'm assuming that your API returns UTC time. From here, we can use UTC at the end of a standard JavaScript parseable date. When str is the string from the API:
var date = new Date(str.substring(0, 10)+" "+str.substring(11, 19)+" UTC")
I'm sure there are better solutions but this manually cuts out the parts you don't need. You can access this Date
object to extract what you need.

101arrowz
- 1,825
- 7
- 15