JavaScript Date.prototype.toISOString()失去偏移 [英] JavaScript Date.prototype.toISOString() loses offset

查看:44
本文介绍了JavaScript Date.prototype.toISOString()失去偏移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此方法使用UTC时区( Z )而不包含本地时间偏移( +/- HH:SS )?方法名称引用的 ISO 8601—允许时区名称" 表示为一部分格式.

Why does this method use UTC timezone (Z) and not include the local time offset (+/-HH:SS) instead? The "ISO" in the method name refers to ISO 8601—which allows for "time zone designations" to be expressed as part of its format.

换句话说, new Date()告诉我日期和时间以及时区偏移量(通过 getTimezoneOffset()).但是 toISOString()仅告诉我一个时区中的日期和时间,它会丢弃 new Date()在语言环境中的时间信息.起源.

In other words, new Date() tells me both the date and time, and the timezone offset (via getTimezoneOffset()). But toISOString() only tells me the date and time in one timezone—it discards the information of what time it was in the locale that the new Date() originated.

toISOString()还包括原始时区与UTC的偏移量是否有意义?如果将 toISOString()省略+/- HH:SS,则会丢失有关起源 Date 的信息.

Wouldn't it make sense for toISOString() to also include the originating timezone's offset from UTC? toISOString()'s omission of +/-HH:SS loses information about the originating Date if it's used for serializing.

我所有的AJAX调用(Angular,jQuery)都通过 toISOString()进行序列化,从而在将序列化日期传递给服务器时丢失了序列化日期的本地时间.任何获取JavaScript <日期>日期来输出ISO格式的字符串的方法,该字符串还包括偏移量(使用Moment.js之类的库除外),还是我需要编写我的自己的方法?

All my AJAX calls (Angular, jQuery) serialize via toISOString(), thus losing the local time of the serialized date when it's communicated to the server. Any way to get a JavaScript Date to output an ISO-formatted string that also includes offset (besides using a library like Moment.js), or do I need to write my own method?

推荐答案

这是因为这是语言规范所说的内容"之一(请参阅

This is one of those "because that's what the language specification says" answers (see ECMA-262 §20.3.4.36). ISO 8601 is a format, and while it allows the use of timezone data, ECMAScript only uses UTC. You can extend Date.prototype with your own toLocalISOString method if you wish. BTW, writing such a method is not difficult.

// Format date as ISO 8601 long format with local timezone offset
if (!Date.prototype.toLocalISOString) {
  Date.prototype.toLocalISOString = function() {
  
  // Helper for padding
  function pad(n, len) {
    return ('000' + n).slice(-len);
  }

  // If not called on a Date instance, or timevalue is NaN, return undefined
  if (isNaN(this) || Object.prototype.toString.call(this) != '[object Date]') return;

  // Otherwise, return an ISO format string with the current system timezone offset
  var d = this;
  var os = d.getTimezoneOffset();
  var sign = (os > 0? '-' : '+');
  os = Math.abs(os);

  return pad(d.getFullYear(), 4) + '-' +
         pad(d.getMonth() + 1, 2) + '-' +
         pad(d.getDate(), 2) +
         'T' + 
         pad(d.getHours(), 2) + ':' +
         pad(d.getMinutes(), 2) + ':' +
         pad(d.getSeconds(), 2) + '.' +
         pad(d.getMilliseconds(), 3) + 
       
         // Note sign of ECMASCript offsets are opposite to ISO 8601
         sign +
         pad(os/60 | 0, 2) + ':' +
         pad(os%60, 2);
  }
}
document.write(new Date().toLocalISOString())

基于DanDascalescu的帖子,这是一种替代方法,它可能会更有效,因为它具有较少的函数调用,但它会创建两个其他的Date对象:

Based on a post by DanDascalescu, here's an alternative that might be more efficient as it has fewer function calls, but it creates two additional Date objects:

// Return a string in ISO 8601 extended format with the host timezone offset
Date.prototype.toLocalISOString = function() {

    // If not called on a Date instance, or timevalue is NaN, return undefined
    if (isNaN(this) || Object.prototype.toString.call(this) != '[object Date]') return;

    // Copy date so don't modify original
    var d = new Date(+this);
    var offset = d.getTimezoneOffset();
    var offSign = offset > 0? '-' : '+';
    offset = Math.abs(offset);
    var tz = offSign + ('0' + (offset/60|0)).slice(-2) + ':' + ('0' + offset%60).slice(-2)
    return new Date(d.setMinutes(d.getMinutes() - d.getTimezoneOffset())).toISOString().slice(0,-1) + tz; 
}

console.log(new Date().toLocalISOString())

这篇关于JavaScript Date.prototype.toISOString()失去偏移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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