将日期时间格式化为带有时区信息的字符串,以使用Javascript创建的日期 [英] Formatting DateTime to string with timezone information for Date created in Javascript

查看:144
本文介绍了将日期时间格式化为带有时区信息的字符串,以使用Javascript创建的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个过于简化的示例中,我有一个接受DateTime的控制器方法

In this massively oversimplified example, I have a controller method that accepts a DateTime

[Route("api/demo)]
public IHttpActionResult Post(DateTime date)
{
   // format dateTime here
}

我们使用Javascript从客户端调用它.

We call this from the client with Javascript.

var data = {
    date: new Date()
};

$.ajax({
    url: "/api/demo",
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: JSON.stringify(data),
});

我觉得 new Date()部分是重要的部分,因为我们正尝试记录主叫客户看到的日期(其本地时间)

The new Date() part is what I feel is the important part, as we're trying to record the date as the calling client sees it (their local time)

将DateTime对象格式化为字符串的最佳方法是什么,以便它记录时区信息,并在以后需要时可以再次解析为 DateTime 对象?

What is the best way to format the DateTime object as a string, so that it records the timezone information, and can be parsed back into a DateTime object again later if required?

(我们正在将此格式化的字符串存储在分析记录平台/数据仓库中)

(We're storing this formatted string in an analytics recording platform / data warehouse)

推荐答案

您无需执行任何转换,只需将参数类型更改为

You don't need to perform any conversions, just change the parameter type to DateTimeOffset:

[Route("api/demo)]
public IHttpActionResult Post(DateTimeOffset date)
{
    //use the date without conversions.
}

JSON.stringify使用可直接解析为DateTimeOffset的ISO8601格式(例如"2017-01-10T14:52:04.780Z" )序列化日期.DateTimeOffset允许您直接比较具有不同偏移量的值,而无需转换为相同时区

JSON.stringify serializes the date using the ISO8601 format (eg "2017-01-10T14:52:04.780Z") which can be parsed directly to a DateTimeOffset. DateTimeOffset allows you to compare values with different offsets directly, removing the need to convert to the same timezone

通过使用DateTimeOffset,可以避免本地和UTC DateTime值之间的混淆.不知道时区偏移量,您真的不知道本地"指的是客户端还是服务器的时区?

By using DateTimeOffset you avoid the confusion between local and UTC DateTime values. Without knowing the timezone offset you don't really know what "local" refers to - the client's or the server's timezone?

这篇关于将日期时间格式化为带有时区信息的字符串,以使用Javascript创建的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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