简体   繁体   中英

how to convert milliseconds to gmt time using javascript

I have a project where if the end date is set for February 12 (can be set to any future date), the following is obtained from the API response.

project: {endDateTime:"1518393600000"}

For UTC time and date, this response corresponds to Mon Feb 12 2018 00:00:00

For local time and date, the response corresponds to Sun Feb 11 2018 19:00:00 (GMT - 05:00)

On the UI, I need to show the end date as Feb 12, 2018, but the date is getting converted to the local date and time zone and shows Feb 11 as the end date. My code is below:

var d = new Date();  
var c = d.setTime(parseInt($scope.project.endDateTime));  
$scope.endDateTime = c;

In the html

<div> {{endDateTime}} </div>  

I tried modifying the code in the following way but it did not work.

 var d = new Date($scope.project.endDateTime);
 var c = d.getUTCDate();
 $scope.endDateTime = c;  

I tried to tune the code in other ways but could not get it to work. I know similar questions have been asked before but still could not get it to work, even after spending several hours. Maybe I am missing something very trivial. Some help would be greatly appreciated. :)

I have figured out the solution. My code and explanation is as follows

var d = new Date(parseInt($scope.project.endDateTime));
var c = c.toUTCString();
var endDate= c.split(" ");
$scope.endDateTime = endDate[2] + ' ' + endDate[1] + ',' + ' ' + endDate[3];  

And the html is

<div> {{endDateTime}}</div>  

I needed to parse the string that came back from the API response. Missed this part and also the correct method is toUTCString() , not getUTCDate() .

So basically what happens is if the end date is set to Feb 12(in this case, it is dynamic though), the API returns

project: {endDateTime:"1518393600000"}

The first line of the code parses the string and if I do a console.log(d) I get this: Sun Feb 11 2018 19:00:00 GMT-0500 (Eastern Standard Time) .

Now I need to display the time in GMT so the toUTCString() method was used in the second line and doing console.log(c) I get: Mon, 12 Feb 2018 00:00:00 GMT

The requirement is to show the date as Feb 12, 2018 on the UI, so I split the string in the third line and if i do console.log(endDate) I get

["Mon,", "12", "Feb", "2018", "00:00:00", "GMT"]

From the output of the third line, it was pretty easy to show the required date format. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM