c# - 在 C# 中格式化日期时间

标签 c# formatting date-formatting

我只是想把一串日期改成DateTime。

但是,当我尝试打印时,它总是说结果是 5/31/20098:00:00 AM

知道为什么会这样吗?

namespace Test
{
    class Test
    {
        static void Main()
        {
            Parse("5/31/2009 12:00:00 AM" );
        }

        static readonly string ShortFormat = "M/d/yyyy hh:mm:ss tt";

        static readonly string[] Formats = { ShortFormat };

        static void Parse(string text)
        {
            // Adjust styles as per requirements
            DateTime result = DateTime.ParseExact(text, ShortFormat,
                                                  CultureInfo.InvariantCulture,
                                                  DateTimeStyles.AssumeUniversal);
            Console.WriteLine(result);
            Console.WriteLine(result);
        }
    }
}

最佳答案

如果您希望解析的DateTime 不考虑时区,您需要使用DateTimeStyles.NoneDateTimeStyles.AssumeLocal:

DateTime result = DateTime.ParseExact(text, ShortFormat,
                                      CultureInfo.InvariantCulture,
                                      DateTimeStyles.None);

当您使用 DateTimeStyles.AssumeUniversal 时,会根据计算机时区进行自动时区转换。

参见 the documentation :

AssumeUniversal - If no time zone is specified in the parsed string, the string is assumed to denote a UTC.

关于c# - 在 C# 中格式化日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10583009/

相关文章:

c# - C#中的基本线程

c# - C# default 关键字在 F# 中的等价物是什么?

c - 在 C 中格式化 double ,如 xxxxE+xx

excel - 在 token 函数中产生多个值(MS excel)

java - 如何更改 SimpleDateFormat 使用的月份名称的大小写?

c# - 如果我的结构不在 COM Interop 中执行,我应该为我的结构使用 LayoutKind.Auto 吗?

Python 字符串格式 - 类型错误 - 格式字符串参数不足

java - SimpleDateFormat 日期解析不正确?

datetime - 根据 UTC 获取 future 事件的本地时间

c# - 如何在 ShowDialog() 阻塞调用之前注册消息处理程序?