mimic
mimic

Reputation: 5224

C#: How to convert string to date accordingly to the giver format?

I have 2 strings: one is date value like "20101127", the second is format "yyyymmdd". How could I extract the date from the value using the given format?

Thanks

Upvotes: 3

Views: 268

Answers (3)

Kobi
Kobi

Reputation: 138117

Use DateTime.ParseExact:

DateTime time = DateTime.ParseExact("20101127", "yyyyMMdd", null);

null will use the current culture, which is somewhat dangerous. You can also supply a specific culture, for example:

DateTime time = DateTime.ParseExact("20101127", "yyyyMMdd", CultureInfo.InvariantCulture);

Upvotes: 5

Phil Hunt
Phil Hunt

Reputation: 8541

Use DateTime.ParseExact(). Note that month is MM, not mm.

var dateValue = DateTime.ParseExact("20101127", "yyyyMMdd",
    CultureInfo.InvariantCulture);

Upvotes: 2

Andrew Hare
Andrew Hare

Reputation: 351586

Use the ParseExact method.

Upvotes: 1

Related Questions