Rudy
Rudy

Reputation: 7044

Format Date Time in C#

I just wanted to change one string of date to DateTime.

However when I try to print, it always said that the result is 5/31/20098: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);
        }
    }
}

Upvotes: 3

Views: 518

Answers (6)

osos95
osos95

Reputation: 169

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

DateTimeStyles.AssumeLocal

instead of:

DateTimeStyles.AssumeUniversal

Upvotes: 0

Oded
Oded

Reputation: 498904

You need to use DateTimeStyles.None or DateTimeStyles.AssumeLocal if you want the DateTime parsed to not take account of timezones:

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

When you use DateTimeStyles.AssumeUniversal an automatic timezone conversion occurs against the computer timezone.

See the documentation:

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

Upvotes: 4

ABH
ABH

Reputation: 3439

All the DateTime formats are described here and here. You should instead use

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

Upvotes: 0

user672118
user672118

Reputation:

In order to print a DateTime in a specified format you need to use the ToString method. 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.

Upvotes: 1

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48558

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

Upvotes: 0

Oliver
Oliver

Reputation: 11597

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

Upvotes: 2

Related Questions