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

折月煮酒 提交于 2021-02-05 07:10:23

问题


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.


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/36880730/how-to-get-date-in-utc-format-irrespective-of-current-system-date-with-javascrip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!