c# - 通过 View 模型接收 DateTime 输入的最佳实践是什么?

标签 c# datetime asp.net-web-api json.net

我有一个 View 模型,其中一个属性是 DateTime。我想允许请求者在他们想要的任何时区发送 DateTime。在我这边,我想将该日期时间转换为 UTC,如果时区信息没有随日期一起到达,则假设它是 UTC。

或者,我可以将发布的 DateTime 限制为 UTC 或至少包含时区信息的内容。

我的后端使用 UTC 格式的所有日期,以 UTC 格式返回它们,这也是它保存的方式。这个问题是关于接收“客户端”输入以及接受日期并将其转换为或确保其为 UTC 的最佳做法是什么。

这是我现在拥有的

public class MyViewModel
{
    /// <summary>
    /// Start date, in UTC.
    /// </summary>
    [Required]
    [DataType(DataType.Date)]
    public DateTime StartDate { get; set; }
}

在 Controller 中:

// Convert to UTC
model.StartDate = model.StartDate.ToUniversalTime();

我想我也可以通过添加构造函数在 View 模型本身中执行此操作。

通过 View 模型接收 DateTime 输入的最佳实践是什么?最终我想确保我收到的是 UTC。

最佳答案

如果您的应用程序要在多个时区使用,我建议将 UTC 日期时间对象保存在数据库中。

将此 UTC 日期时间对象转换为本地日期时间的常见做法。

输入

API 应采用 ISO 8601 格式作为输入 as mentioned in this blog .

prefer ISO 8601 (yyyy-MM-dd'T'HH:mm:ssZ) because it’s human readable and has a specified timezone. There is no ambiguity if the epoch is in seconds or milliseconds. ISO 8601 strings are encoded in a way that enable decent string sorting and comparison.

输出

我相信你想知道 web api 应该如何返回 DateTime 对象。

在我看来,RESTful API 应该独立于时区,并且应该以 UTC 格式返回日期。

调用此 API 的手机应用/桌面应用/网络应用应负责以正确的时区格式显示日期。

但是,正如前面的评论所述,这个决定是由您的应用程序设计驱动的。

希望对您有所帮助。

关于c# - 通过 View 模型接收 DateTime 输入的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55268300/

相关文章:

c# - 使用 DotNetOpenAuth 保护的 WCF 4 Soap 和 Json 端点

c# - 如何在 EF 上运行 SQL 查询?

c# - 在 C# 中使用 Silverlight?

javascript - 检查 Javascript 中的干扰时间跨度?

.net - JSON 序列化 - 删除空键

asp.net - 为什么.Net WebApi 不自动检测请求内容类型并进行自动绑定(bind)?

c# - 将按钮文本更改为连续数字 0-9

python - 无法在日期时间字段中使用 python 和 mysql 插入无

android - MonthDisplayHelper.NumberOfDaysInMonth 在 MonoDroid 中返回不正确的值

c# - .Net Core 1.0 中 Web API 的版本控制