Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting UTC time giving me NaN

Tags:

javascript

Why am I getting NaN with the following code?

var currentTime = new Date();
var utcTime = Date.UTC(currentTime);
console.log(utcTime);

Basically, I want to get a date/time value in UTC. What's the best way to get that?

like image 566
Sam Avatar asked Feb 26 '17 02:02

Sam


Video Answer


1 Answers

console.log(new Date().toUTCString());

Dates already use UTC time internally. They store the number of milliseconds since Jan 1 1970 0:00:00 UTC. So, whether you want to show the local time or the UTC time only becomes relevant when wanting to show the value to a user.


When sending DateTime values to a ASP.net API, there are two cases:

Newer ASP.net versions use JSON.net for JSON Serializing. They understand the ISO 8601 format. So, use

var value = new Date().toISOString();

Older ASP.net versions use a Microsoft specific format that you can generate like this:

function makeMSDateFormat(date)
{
    return "\/Date(" + date.getTime() + ")\/";
}

var value = makeMSDateFormat(new Date());

Some Background information

like image 116
NineBerry Avatar answered Oct 19 '22 20:10

NineBerry