javascript json 和 Utc 日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15725090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:51:17  来源:igfitidea点击:

json and Utc datetime

javascriptasp.net-mvcjsonutc

提问by agri

I'm storing Utc datetime on the server and requesting data via json to display on client. The problem is that the server returns the time by its timezone which is different to a client. How could I get the local dateTime to display on client without hardcoding the offset?

我在服务器上存储 Utc 日期时间并通过 json 请求数据在客户端上显示。问题是服务器按与客户端不同的时区返回时间。如何在不硬编码偏移量的情况下让本地日期时间显示在客户端上?

I'm using asp.net mvc and stroring date and time in SQL Server 2008 database as 'datetime'. DateTime format in database is 2013-03-29 08:00:00.000.

我正在使用 asp.net mvc 并将 SQL Server 2008 数据库中的日期和时间作为“日期时间”。数据库中的日期时间格式为 2013-03-29 08:00:00.000。

回答by RobG

You don't say how the UTC time is represented. It's common to use a UNIX time value that is seconds since 1970-01-01T00:00:00Z. If that is what you are using, you can create a date object on the client by multiplying by 1,000 and giving it to the Date constructor:

你没有说 UTC 时间是如何表示的。通常使用自 1970-01-01T00:00:00Z 以来的秒数的 UNIX 时间值。如果这是您正在使用的,您可以通过乘以 1,000 并将其提供给 Date 构造函数来在客户端上创建一个日期对象:

var unixTimeValue = '1364694508';
var clientDateObject = new Date(unixTimeValue * 1000);

If you are using say .NET, the value may already be in milliseconds so you don't need to multiply by 1,000. You need to check with the source to see what value is passed and what epoch is used if it's a time value.

如果您使用的是 .NET,则该值可能已经以毫秒为单位,因此您无需乘以 1,000。您需要检查源以查看传递的值以及使用的时间值(如果它是时间值)。

Javascript date objects are based on a time valuethat is the same epoch as UNIX, but uses milliseconds. The standard Date methods (getFullYear, getMonth, getDate, etc.) will return values in the local timezone based on system settings. The UTC methods (getUTCFullYear, getUTCMonth, getUTCDate, etc.) return UTC values for the same time.

Javascript 日期对象基于与 UNIX 相同的时代的时间值,但使用毫秒。标准日期方法(getFullYear、getMonth、getDate 等)将根据系统设置返回本地时区中的值。UTC 方法(getUTCFullYear、getUTCMonth、getUTCDate 等)同时返回 UTC 值。

So if you are passing a time value, use it to create a date object on the client and read the values using standard methods and you have local equivalents of the UTC time value.

因此,如果您要传递时间值,请使用它在客户端上创建日期对象并使用标准方法读取值,并且您拥有 UTC 时间值的本地等效项。

If you are passing a datetime string like 2013-03-31T14:32:22Z, you can convert that to a date object using Date.UTCto convert the string to a time value, then give that to the date constructor:

如果您要传递像 2013-03-31T14:32:22Z 这样的日期时间字符串,您可以使用Date.UTC将其转换为日期对象,以将字符串转换为时间值,然后将其提供给日期构造函数:

function dateFromUTCString(s) {
    s = s.split(/[-T:Z]/ig);
    return new Date(Date.UTC(s[0], --s[1], s[2], s[3], s[4], s[5]));
}

var s = '2013-03-31T14:32:22Z';
alert(dateFromUTCString(s));  // Mon Apr 01 2013 00:32:22 GMT+1000 (EST)

If your input string is a different format, you may need to adjust the split pattern and order of parameters passed to Date.UTC.

如果您的输入字符串是不同的格式,您可能需要调整传递给 Date.UTC 的参数的拆分模式和顺序。

Edit

编辑

If the string format is 2013-03-29 08:00:00.000 (assuming UTC), you can use:

如果字符串格式为 2013-03-29 08:00:00.000(假设为 UTC),则可以使用:

function dateFromUTCString(s) {
    s = s.split(/[\D]/ig);
    return new Date(Date.UTC(s[0], --s[1], s[2], s[3], s[4], s[5], s[6]||0));
}

var s = '2013-03-29 08:00:00.000';
alert(dateFromUTCString(s));  // Fri Mar 29 2013 18:00:00 GMT+1000 (EST)

But be careful of additional spaces. You might want to trim any leading or trailing spaces and ensure there is only one separating the date and time components.

但要注意额外的空间。您可能想要修剪任何前导或尾随空格,并确保只有一个分隔日期和时间组件。

Edit 2

编辑 2

Don't use Date.parse. Until ES5 it was completely implementation dependent. Now it's partially standardised ifthe string complies with the ISO8601–like format specified by ES5. But that isn't supported by all browsers in use, so not reliable and is otherwise still implementation dependent. The best solution (i.e. one that will work everywhere) is to manually parse the value you are given.

不要使用 Date.parse。在 ES5 之前,它完全依赖于实现。现在,如果字符串符合 ES5 指定的类似 ISO8601 的格式,则它已部分标准化。但这并不是所有正在使用的浏览器都支持,所以不可靠,否则仍然依赖于实现。最好的解决方案(即适用于任何地方的解决方案)是手动解析给定的值。

If the format is like: "1364835180000-0700", then you can fairly easily deal with that using a function that subtracts the offset to get UTC time value, the gives that to the date constructor. I'm assuming that -0700 means 7hrs west of Greenwich (javascript timezone offsets have an opposite sense, west of Greenwich is +ve).

如果格式类似于:“1364835180000-0700”,那么您可以使用减去偏移量以获取 UTC 时间值的函数轻松处理该问题,并将其提供给日期构造函数。我假设 -0700 表示格林威治以西 7 小时(javascript 时区偏移量具有相反的意义,格林威治以西为 +ve)。

Edit 3

编辑 3

Sorry, must have posted the wrong snipped, rushing to a meeting.

不好意思,一定是贴错了,急着开会。

// Where s is a time value with offset
function toDate(s) {

  // Include factor to convert mins to ms in sign
  var sign = s.indexOf('-') > -1? 6e4 : -6e4;
  s = s.split(/[\+\-]/);
  var l = s[1].length;

  // Convert offset in milliseconds
  var offset = sign*s[1].substring(l-2,l) + sign*s[1].substring(l-4, l-2)*60;

  // Add offset to time value to get UTC and create date object 
  return new Date(+s[0] + offset);
}

var s = "1364835180000-0700"
alert(toDate(s)); // Tue Apr 02 2013 09:53:00 GMT+1000 (EST)

回答by Rob G

Return the DateTime as UTC and convert it on the client using .toLocaleString():

将 DateTime 作为 UTC 返回并在客户端使用 .toLocaleString() 进行转换:

  @ViewBag.Time = Model.Time.ToUniversalTime().Ticks / TimeSpan.TicksPerMillisecond

  <script>
       var time = new Date(@ViewBag.Time);
       var localTimeString = time.toLocaleString();
       alert(localTimeString);
  </script>