0

From the server I am getting a DateTime in this format: 2019-07-11T05:33:53.45 and it is in UTC time.

I want to convert it to the current user’s browser time using JavaScript in the format like 11th July 2019 11:03 AM which is UTC+0530 for Indian time for given time(2019-07-11T05:33:53.45).

I have tried Intl.DateTimeFormat and also other JavaScript date time functions eg. toLocaleString. But I am getting the time in UTC format only. When I get the time as what I want UTC+0530 is also attached, which I don't want.

let d = new Date(date_from_server);
let options= { year: 'numeric', month: 'numeric', day: 'numeric',
                    hour: 'numeric', minute: 'numeric', second: 'numeric',
                    hour12: false };                    
let ddmmmyy= new Intl.DateTimeFormat('default', options).format(d);

This is one of the solution I tried. I have tried other methods also, but didn't succeed. eg. let ddmmmyy = d.toLocaleString();

I want the time as per User's current browser timezone and in the specified format(11th July 2019 11:03 AM IST).

How can I achieve it? Please help.

jrswgtr
  • 2,287
  • 8
  • 23
  • 49
Chaits14
  • 3
  • 3
  • Possible duplicate of https://stackoverflow.com/questions/6525538/convert-utc-date-time-to-local-date-time – Tyler Youngblood Aug 14 '19 at 14:45
  • Possible duplicate of [Convert UTC date time to local date time](https://stackoverflow.com/questions/6525538/convert-utc-date-time-to-local-date-time) – Sani Huttunen Aug 14 '19 at 14:47

2 Answers2

0

Try this:

var date = new Date('2019-08-14 17:00:34 UTC');
date.toString(); // outputs "Wed Aug 14 2019 13:00:34 GMT-0400 (Eastern Daylight Time)"
Tyler Youngblood
  • 2,710
  • 3
  • 18
  • 24
0

You need to replace the T in the date string and also append UTC.
Then you need to remove GMT and anything after that in the result:

var dateString = "2019-07-11T05:33:53.45".replace('T', ' ') + " UTC"; // or + "Z" instead of + " UTC";
var dateObj = new Date(dateString);
var localDateString = dateObj.toString().replace(/GMT.*/g,"");
console.log(localDateString);
Sani Huttunen
  • 23,620
  • 6
  • 72
  • 79
  • Thanks, this solution works perfectly in Chrome. But it is not working in IE11 and Firefox. Is there any solution to make it work in other browsers also? – Chaits14 Aug 16 '19 at 07:11
  • @Chaits14: Appending `"Z"` instead of `" UTC"` should do the trick. `Z` stands for `Zulu` and comes from the military tradion of using the phonetic alphabet. The letter `Z` is in the phonetical alphabet `Zulu`. Why `Z`? Each time zone is expressed as a certain number of hours `ahead of UTC` or `behind UTC`? (For example, UTC -5 is Eastern Standard Time.) The letter `Z` refers to the Greenwich time zone, which is zero hours (UTC + 0). – Sani Huttunen Aug 17 '19 at 10:15
  • Appending "Z" to the server time fixed my problem. It is working in all the browsers now. – Chaits14 Aug 19 '19 at 10:36