简体   繁体   中英

String to Datetime can not convert - C#

I found an example in MSDN for string to datetime conversion. But it doesn't work, fall into the catch(). Why this code block doesn't work?

DateTime dateValue;
      string dateString = "2/16/2008 12:15:12 PM";
      try {
         dateValue = DateTime.Parse(dateString);
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
      }   
      catch (FormatException) {
         Console.WriteLine("Unable to convert '{0}'.", dateString);
      }

You're using whatever the current culture's idea of a date/time format is - and my guess is that you're in a culture where the day normally comes before the month.

If you know the format, I'd typically use the invariant culture and TryParseExact - definitely don't use Parse and a catch block; either use TryParseExact or TryParse . In this case:

if (DateTime.TryParseExact(dateString, "M/d/yyyy hh:mm:ss tt",
                           CultureInfo.InvariantCulture, 0, out dateValue))
{
    Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
else
{
    Console.WriteLine("Unable to convert '{0}'.", dateString);
}

If you don't know the input format, but you know the culture to use, I'd just use DateTime.TryParse with the appropriate culture.

Try using ParseExact passing the appropriate format provider as in this example :

string dateString = "2/16/2008 12:15:12 PM"; 
    string format = "M/dd/yyyy hh:mm:ss tt ";

    DateTime dateTime = DateTime.ParseExact(dateString, format,
        CultureInfo.InvariantCulture);

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