简体   繁体   中英

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)

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.)

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.

试试DateTime.ParseExact

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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