2/22/2012 3:30:00
Surely that is an acceptable format to be converted to DateTime using Convert.ToDateTime()?
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 prefer1 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...
It should be able to if you supply an IFormatProvider which specifies the culture (e.g. en-US in that case).
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