Elad Benda
Elad Benda

Reputation: 36654

converting messy date string to dateTime object in c#

How can I convert the String 20120313 to a DateTime object that holds the value 13-Mar-2012?

I fetch it as

DataEffectiveDate = Convert.ToDateTime(reader["date_id"]);

But it fails here already (converting to 1/1/2001)

Upvotes: 0

Views: 369

Answers (3)

Matthias
Matthias

Reputation: 12259

Try DateTime.ParseExact:

string date = DateTime.ParseExact(reader["date_id"], "yyyyMMdd", new CultureInfo("en"));

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062875

When you have a particular format in mind, ParseExact is helpful:

string s = "20120313";
var when = DateTime.ParseExact(s, "yyyyMMdd", CultureInfo.InvariantCulture);

There's also an overload that accepts multiple candidate formats.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500755

You need to use DateTime.ParseExact:

DateTime date = DateTime.ParseExact(text, "yyyyMMdd",
                                    CultureInfo.InvariantCulture);

Then if you want it as "13-Mar-2012", you need:

string reformatted = date.ToString("dd-MMM-yyyy");

... optionally passing in whatever culture you want to use for the month names etc.

(Another alternative is to use my Noda Time, which allows you to parse this as just a local date, without any concerns about what time it will use, time zones etc.)

Upvotes: 3

Related Questions