Format Date Time in C #

I just wanted to change one date string to DateTime.

However, when I try to print, he always said that the result 5/31/2009 8:00:00 AM

Any idea why this is happening?

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);
        }
    }
}
+3
source share
6 answers

You need to use DateTimeStyles.Noneor DateTimeStyles.AssumeLocal, if you want the analyzed one DateTimenot to take into account time zones:

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

When used DateTimeStyles.AssumeUniversal, the time zone automatically changes against the time zone of the computer.

See the documentation :

AssumeUniversal - if the time zone is not specified in the parsed line, it is assumed that the line indicates UTC.

+4
source

I think you need to write MM/dd/yyyy hh:mm:ss ttfor the date format.

+2

DateTime , ToString. .

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

(format) , (S) .

+1

All DateTime formats are described here and here . Instead, you should use

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

Change shortformat to

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

Your line means it

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

The number above corresponds to the format below

0
source

It depends on your time zone, and I think your GMT + 4 time zone is not GMT-4, as answered by bukko. Anyway, just use:

DateTimeStyles.AssumeLocal

instead:

DateTimeStyles.AssumeUniversal
0
source

All Articles