c# - 转换为日期时间和从日期时间转换增加一个小时?

标签 c# asp.net datetime datetime-format

我正在 asp.net/c# 中编写一个相当大的 webapp,并使用 MSSQL 2008 r2 为数据库服务。该程序需要将 date/time 字符串(采用 ISO 日期格式)转换为 DateTime 并随后在 中存储为 smalldatetime >sql.

当字符串被转换为datetimes 时,一个hour 神秘地添加到结果中。我知道在英国,我们受制于夏令时(当前有效),但肯定 datetime.convert 方法理解这一点?转换回字符串时,结果符合预期。

我写了一个小程序来说明这个问题(为了我的理智,还包括非 ISO 日期):

class Program
{


    static void Main(string[] args)
    {
        //BB();
        //Dist();
        DateTime d1 = new DateTime();
        DateTime d2 = new DateTime();
        string d1s = "2010-09-13T09:30:01Z";
        string d2s = "2010-09-13 09:30:01";

        d1 = Convert.ToDateTime(d1s);
        d2 = Convert.ToDateTime(d2s);

        Console.WriteLine("d1s:{0} d1:{1} ", d1s, d1);
        Console.WriteLine("d2s:{0} d2:{1} ", d2s, d2);

        d1s = d1.ToString("u"); d2s = d2.ToString("u");

        Console.WriteLine("\nd1: {0}", d1s);
        Console.WriteLine("d2: {0}", d2s);

        d1 = Convert.ToDateTime(d1s);
        d2 = Convert.ToDateTime(d2s);

        Console.WriteLine("\nd1s:{0} d1:{1} ", d1s, d1);
        Console.WriteLine("d2s:{0} d2:{1} ", d2s, d2);

        Console.Read();
    }
}

这是我运行程序时得到的结果:

d1s:2010-09-13T09:30:01Z d1:13/09/2010 10:30:01
d2s:2010-09-13 09:30:01 d2:13/09/2010 09:30:01

d1: 2010-09-13 10:30:01Z
d2: 2010-09-13 09:30:01Z

d1s:2010-09-13 10:30:01Z d1:13/09/2010 11:30:01
d2s:2010-09-13 09:30:01Z d2:13/09/2010 10:30:01
Done

这是正确的行为吗?我是白痴吗?我本来希望将 datetime 转换为字符串,然后将确切的字符串返回到 datetime 会返回原始输入。如果这是正确的行为,关于如何获得一致的结果但仍然使用 Convert.ToDateTime() 有什么想法吗?

非常感谢。

最佳答案

日期时间末尾的“Z”表示“Zulu”(相当于 UTC/GMT)。默认情况下,当您转换字符串末尾的字符串时,它会将其转换为本地时间(在您的情况下为 + 1 小时)。

如果没有“Z”,.NET 将假设日期已经采用正确的格式并且不会添加小时。

当您将日期时间格式化回字符串时,您使用的是格式字符串“U”。这是在告诉 .NET 现在是 UTC 时间,应该按照这样的格式进行格式化。因此它在末尾添加了“Z”。当您将其转换回日期时间时,会添加另一个小时以使其成为本地时间。

澄清一下:

d1:以 UTC 字符串开头 -> 本地时间(+ 1 小时) -> UTC 字符串 -> 本地时间(+1 小时)

d2:以本地字符串开始 -> 本地时间(无变化) -> UTC 字符串 -> 本地时间(+ 1 小时)

关于c# - 转换为日期时间和从日期时间转换增加一个小时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3700041/

相关文章:

c# - Microsoft.Azure.Storage.StorageException : The account being accessed does not support http

c# - Azure Signalr +Azure function + wpf 客户端 - 如何使用 azure function 和自托管 Azure SignalR App 拥有 wpf 客户端应用程序

c# - Autofac:使用非泛型接口(interface)注册泛型类型

c# - 使用参数动态加载用户控件

python - 如何在 Pandas 中选择 'last business day of the month'?

c# - 在 WCF 服务中添加自定义构造函数并在客户端(asp.net 或 Windows 窗体)上访问它

c# - 在 asp.net 视频上创建控件时出错

c# - Ghostscript.NET pdf 到图像在 Windows Azure 上无法工作

MySQL查询每月选择一组项目

c++ - 如何使用 C++ 将日期设置为我选择的下一个工作日?