3

我使用 Javascript 函数将日期转换为 UTC 日期,如下所示:

Date.prototype.convertToUTC = function () {
var month = this.getMonth();
var day = this.getDate();
var year = this.getFullYear();
return new Date(Date.UTC(year, month, day));
}

现在,当应用此函数的日期已经是 UTC 时,就会出现问题。由于我不知道用户是否会在 UTC/Local 日期调用此方法,因此我想确保只有在不是 UTC 时才会发生转换。请帮忙。

4

2 回答 2

1

All dates have a UTC time value at their heart. Date objects created in a host are given a read–only timezone offset based on the system settings, and values read using getDate, getHours, etc. are based on that offset.

If you want UTC milliseconds since the epoch, just use the getTime() method. Alternatively, there are the UTC methods, getUTCDay, getUTCHours, etc. to build your own formatted string.

Finally, there is toISOString which should return an ISO formatted date string for UTC, but support may be lacking in not so old browsers.

Some examples

To create a local date object for 2012-11-06T15:45:01Z:

var date = new Date(Date.UTC(2012, 10, 6, 15, 45, 1));

To get an ISO date string from that (or any) date object:

var isoString = date.toISOString();

To get a UTC time value in milliseconds (ms since 1970-01-01T00:00:00Z):

var timeValue = date.getTime();

To turn that time value back into a local date object:

var date = new Date(timeValue);
于 2012-11-06T09:32:23.567 回答
1

JavaScript Date object has the method getTimezoneOffset(). You could use that. Or use the getUTC* methods:

 var d = new Date();
 var utcyear = d.getUTCFullYear();
于 2012-11-06T09:33:41.483 回答