简体   繁体   中英

How to get date in UTC format irrespective of current system date with javascript?

I am trying to get the current date in UTC format. SO far I am able to do it but what I am stuck with is that it checks for the current 'System Date' and returns the result. I do not want that to happen because I need it specifically in UTC format and not by getting the system date.

Also, the format I have output the result is the one I want with no changes in it. Any suggestions would be of great help.

Here is my code:

var now = new Date();
var currentDate;
var date = (new Date(now) + '').split(' ');
date[0] = date[0] + ',';
date[2] = date[2] + ',';
currentDate = [date[0], date[1], date[2], date[3]].join(' ');
return currentDate;

This returns as Wed, Apr26, 2016. If this code is run somewhere else with a time difference of say +-12, the date will be that system date in UTC which I do not want.

The only way to keep the formatting consistent across browsers is to either build a small utility function using the Date#getUTC* functions or use a library that does this for you. I would go with the former. You could use something like this:

function getUTCDateString(){
    var d = new Date();
    var days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    var month  = ['Jan', 'Feb', 'Mar', 'April', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

    return (
        days[d.getUTCDay()-1]
        + ', ' + month[d.getUTCMonth()]
        + d.getUTCDate() 
        + ', ' + d.getUTCFullYear()
        );
}

If you do any localized programming things quickly increase in complexity and bringing in some of the libs mentioned makes more sense.

If you need to keep the output you mentioned, check this out:

var dateString = new Date().toUTCString().split(' ');
return dateString[0] + " " + dateString[2] + dateString[1] + ", " + dateString[3];

There are some other useful UTC methods for Dates here .

Have you looked into momentjs? It's a date object wrapper that makes manipulating dates easy. Just use the utc() function provided. http://momentjs.com/docs/#/manipulating/utc/

After installing moment through npm, here's what sample code will look like:

var moment = require("moment");

 var utcNow = moment().utc();

 console.log(utcNow);

This will output current utc date

I would recommend calling the toISOString() method on the date instance. Here's the code

var now = new Date,
    isoNow = now.toISOString();
console.log(now, isoNow); // Wed Apr 27 2016 10:50:29 GMT+0530 (IST) "2016-04-27T05:20:29.146Z" 

So you have universal time here

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