使用javascript,无论当前系统日期如何,如何以UTC格式获取日期? [英] How to get date in UTC format irrespective of current system date with javascript?

查看:43
本文介绍了使用javascript,无论当前系统日期如何,如何以UTC格式获取日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以UTC格式获取当前日期.到目前为止,我能够做到,但是我坚持的是它会检查当前的系统日期"并返回结果.我不希望发生这种情况,因为我特别需要UTC格式的文件,而不是通过获取系统日期来实现.

另外,我输出的结果格式是我想要的格式,没有任何更改.任何建议都会有很大帮助.

这是我的代码:

  var现在= 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('');返回currentDate; 

这将返回为2016年4月26日,星期三.如果此代码在其他地方运行且时差为+ -12,则日期将是我不希望使用的UTC系统日期.

解决方案

在所有浏览器中保持格式一致的唯一方法是使用 Date#getUTC * 函数构建一个小的实用程序函数,或者使用为您执行此操作的库.我会和前者一起去.您可以使用类似这样的内容:

  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'];返回 (天[d.getUTCDay()-1]+','+月[d.getUTCMonth()]+ d.getUTCDate()+','+ d.getUTCFullYear());} 

如果您进行任何本地化编程,事情都会迅速增加复杂性,并且引入其中提到的某些库更有意义.

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.

这篇关于使用javascript,无论当前系统日期如何,如何以UTC格式获取日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆