简体   繁体   English

格式化日期时间C#

[英]Format Date Time in C#

I just wanted to change one string of date to DateTime. 我只想将一个日期字符串更改为DateTime。

However when I try to print, it always said that the result is 5/31/2009 8:00:00 AM 但是,当我尝试打印时,它总是说结果是5/31/2009 8:00:00 AM

Any idea why this thing happens? 知道为什么会发生这件事吗?

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);
        }
    }
}

You need to use DateTimeStyles.None or DateTimeStyles.AssumeLocal if you want the DateTime parsed to not take account of timezones: 如果希望解析的DateTime不考虑时区,则需要使用DateTimeStyles.NoneDateTimeStyles.AssumeLocal

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

When you use DateTimeStyles.AssumeUniversal an automatic timezone conversion occurs against the computer timezone. 使用DateTimeStyles.AssumeUniversal时,会对计算机时区进行自动时区转换。

See the documentation : 查看文档

AssumeUniversal - If no time zone is specified in the parsed string, the string is assumed to denote a UTC. AssumeUniversal - 如果在解析的字符串中未指定时区,则假定该字符串表示UTC。

我想你需要写日期格式的MM/dd/yyyy hh:mm:ss tt

In order to print a DateTime in a specified format you need to use the ToString method. 要以指定格式打印DateTime ,您需要使用ToString方法。 Like so. 像这样。

result.ToString("M/d/yyyy hh:mm:ss tt");

The second parameter ( format ) defines the format that the string ( S ) must be in for it to be parsed. 第二个参数( format )定义了字符串( S )必须用于解析的格式。

All the DateTime formats are described here and here . 此处此处描述所有DateTime格式。 You should instead use 你应该改用

static readonly string ShortFormat = "MM/dd/yyyy hh:mm:ss tt";

Change shortformat to 将短格式更改为

static readonly string ShortFormat = "MM/dd/yyyy hh:mm:ss tt";

Your string stand for this 你的字符串代表了这一点

"05/31/2009 12:00:00 AM"
"MM/dd/yyyy hh:mm:ss tt"

Number on top corresponds to format below 顶部的数字对应于下面的格式

It depends on your time zone, and I think your time zone is GMT+4 not GMT-4 as bukko answered. 这取决于你的时区,我认为你的时区是GMT + 4而不是GMT-4,因为bukko回答。 Anyway, just use: 无论如何,只需使用:

DateTimeStyles.AssumeLocal

instead of: 代替:

DateTimeStyles.AssumeUniversal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM