在javascript中处理日期(格式和时区)

Handling dates (formatting and timezones) in javascript

本文关键字:格式 时区 日期 javascript 处理      更新时间:2023-09-26

用例是,我通过ajax调用获得以毫秒为单位(从epoch)的日期,现在需要在javascript中进行解释。这对应于UTC的某个时间点

现在我需要在PST中显示此日期,因为这是用户唯一相关的时区,无论他们从哪里打开页面。此外,我需要以不同的格式显示它,如'yyyy-mm-dd HH:mm',而不是默认的Locale字符串。

谁能告诉我,我该怎么做?

使用UNIX毫秒值加上到PST的偏移量创建一个新的日期,然后使用getUTC系列调用创建格式化字符串

Moment.js对于这类事情来说是一个非常好的库。

我相信时区是由用户在使用新的Date()函数时设置的时区决定的。

var myDateTime = 1312312732923; 
var myDate = new Date(myDateTime); 
var myFormattedDate = myDate.getFullYear() + "-" + (myDate.getMonth()+1) + "-" + myDate.getDay();
http://www.w3schools.com/jsref/jsref_obj_date.asp

JavaScript现在可以设置要显示的内容所在的时区。我使用了Flot作为图表库,他们建议的解决方案是在显示日期时使用getUTC方法。这意味着您的服务器代码不能从epoch发送标准毫秒(因为它将显示GMT时间),但是服务器上的一个小调整将使您的日期在客户端上正确显示。

要了解该问题,请参阅http://flot.googlecode.com/svn/trunk/API.txt,并查找标题"时间序列数据"

使用Date对象:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

Javascript的Date对象使用毫秒而不是秒,因此您必须将UNIX时间戳乘以1000:

var myDate = new Date(unix_timestamp * 1000);

然后,您可以使用特定于本地的Date对象来做任何您想做的事情:

var output = myDate .getHours() + ':';
output += myDate .getMinutes() + ':';
output += myDate .getSeconds();
alert(output);

EDIT啊,忽略了始终使用PST的部分,无论语言环境如何。unix_timesamp还是从服务器获取的epoch/UNIX时间戳:

试试:http://jsfiddle.net/46PYZ/

  // set to the UTC offset for the target timezone, PST = UTC - 8
    var target_offset = -8;
    // create a Date object
    var myDate = new Date();
    // add local time zone offset to get UTC time in msec
    var utc_milliseconds = (unix_timesamp * 1000) + (myDate .getTimezoneOffset() * 60000);
    // set the time using the calculated UTC timestamp
    myDate.setTime(utc_milliseconds + (3600000 * target_offset));
    // now build the yyyy-mm-dd HH:mm format
    var output = myDate.getFullYear() + '-';
    var month = myDate.getMonth() + 1;
    output += (month < 10 ? '0' + month : month) + '-';
    output += myDate.getDate() + ' ';
    var hours = myDate.getHours() + 1;
    output += (hours < 10 ? '0' + hours : hours) + ':';
    var minutes= myDate.getMinutes() + 1;
    output += (minutes< 10 ? '0' + minutes : minutes);