简体   繁体   中英

Why won't this string be converted to DateTime?

2/22/2012 3:30:00

Surely that is an acceptable format to be converted to DateTime using Convert.ToDateTime()?

I would personally avoid using Convert.ToDateTime . I generally prefer 1 to use DateTime.TryParseExact , specifying the culture and format string you expect - assuming you have an expected format, of course. If you don't, you have to ask yourself bigger questions.

For example:

DateTime value;
if (DateTime.TryParseExact(text, "M/d/yyyy H:mm:ss",
                           CultureInfo.InvariantCulture,
                           DateTimeStyles.None,
                           out value))
{
    Console.WriteLine("Parsed to {0}", value);
}
else
{
    Console.WriteLine("Failed to parse");
}

That's a slightly odd format to start with - normally a 24-hour format would include a leading 0 for the hour, and a 12-hour format would include an am/pm designator.


1 Well, I prefer to use Noda Time , but that's a different matter...

Surely that is an acceptable format to be converted to DateTime using Convert.ToDateTime()?

Surely not. That would be true for some locales but for example I have a fr-FR locale and this is an invalid date. There are no 22 months in the year. Make sure you specify the format when parsing the date. You could use the TryParseExact method for this.

If you got the Information about Year, Month, etc. separately as Integers I would rather use the Constructor of DateTime.

DateTime myDateTime  = new DateTime(year, month, day, hour, minute, second);

Usually nothing can go wrong with this...

如果您提供一个指定区域性的IFormatProvider,则应该能够(例如,在这种情况下为en-US)。

var date = Convert.ToDateTime("2/22/2012 3:30:00", CultureInfo.GetCultureInfo("en-US"));

Here is an example on how to use Convert.ToDateTime() which will help you to understand it :
Convert.ToDateTime example

Or You can try by following this example :
Convert String to DateTime

This works just fine for me:

            DateTime dt = Convert.ToDateTime("2/22/2012 3:30:00");
        Console.WriteLine(dt.ToShortDateString());
        Console.WriteLine(dt.ToShortTimeString());

Of course I am not paying attention to localization like Darin suggests

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