Date.toISOString(),但使用本地时间而不是UTC [英] Date.toISOString() but local time instead of UTC

查看:47
本文介绍了Date.toISOString(),但使用本地时间而不是UTC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有这个日期时间:

Let's say we have this datetime:

var d = new Date("Sat Jul 21 2018 14:00:00 GMT+0200");

将其导出为字符串( console.log(d))会在浏览器中产生不一致的结果:

Exporting it as a string (console.log(d)) gives inconsistent results among browsers:

  • Sat Jul 21 2018 14:00:00 GMT + 0200(巴黎,马德里(heure d'été))和Chrome

Sat Jul 21 14:00:00 UTC + 0200 2018 和Internet Explorer等.

Sat Jul 21 14:00:00 UTC+0200 2018 with Internet Explorer, etc.

所以我们不能将日期时间发送到格式为不一致的的服务器.

so we can't send datetime to a server with an unconsistent format.

然后自然的想法是要求一个ISO8601日期时间,并使用 d.toISOString(); ,但是它给出了UTC日期时间: 2018-07-21T12:00:00.000Z ,而我想改为本地时区时间:

The natural idea then would be to ask for an ISO8601 datetime, and use d.toISOString(); but it gives the UTC datetime: 2018-07-21T12:00:00.000Z whereas I would like the local-timezone time instead:

2018-07-21T14:00:00+0200
or
2018-07-21T14:00:00

如何获取此信息(不依赖诸如momentjs之类的第三方依赖项)?

我尝试了这种方法,似乎可以工作,但是没有更自然的方法吗?

I tried this, which seems to work, but isn't there a more natural way to do it?

var pad = function(i) { return (i < 10) ? '0' + i : i; };

var d = new Date("Sat Jul 21 2018 14:00:00 GMT+0200");
Y = d.getFullYear();
m = d.getMonth() + 1;
D = d.getDate();
H = d.getHours();
M = d.getMinutes();
S = d.getSeconds();
s = Y + '-' +  pad(m) + '-' + pad(D) + 'T' + pad(H) + ':' + pad(M) + ':' + pad(S);
console.log(s);

推荐答案

ECMA-262中对带有时区的日期字符串进行格式化的内置支持有限,其中既有与实现相关的 toString toLocaleString 方法或 toISOString (始终为UTC).如果 toISOString 允许参数指定UTC或本地偏移量(默认为UTC),那会很好.

There is limited built-in support for formatting date strings with timezones in ECMA-262, there is either implementation dependent toString and toLocaleString methods or toISOString, which is always UTC. It would be good if toISOString allowed a parameter to specify UTC or local offset (where the default is UTC).

编写自己的函数以生成具有本地偏移量的符合ISO 8601的时间戳并不难:

Writing your own function to generate an ISO 8601 compliant timestamp with local offset isn't difficult:

function toISOLocal(d) {
  var z  = n =>  ('0' + n).slice(-2);
  var zz = n => ('00' + n).slice(-3);
  var off = d.getTimezoneOffset();
  var sign = off < 0? '+' : '-';
  off = Math.abs(off);

  return d.getFullYear() + '-'
         + z(d.getMonth()+1) + '-' +
         z(d.getDate()) + 'T' +
         z(d.getHours()) + ':'  + 
         z(d.getMinutes()) + ':' +
         z(d.getSeconds()) + '.' +
         zz(d.getMilliseconds()) +
         sign + z(off/60|0) + ':' + z(off%60); 
}

console.log(toISOLocal(new Date()));

这篇关于Date.toISOString(),但使用本地时间而不是UTC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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