This program is given in the following website.
http://www.dotnetperls.com/datetime-parse
An unhandled exception is occurring at the highlighted statement. Please explain the reason.
using System;
class Program
{
static void Main()
{
// Taken from my head
string simpleTime = "1/1/2000";
DateTime time = DateTime.Parse(simpleTime);
Console.WriteLine(time);
// Taken from HTTP header
string httpTime = "Fri, 27 Feb 2009 03:11:21 GMT";
time = DateTime.Parse(httpTime);
Console.WriteLine(time);
// Taken from w3.org
string w3Time = "2009/02/26 18:37:58";
time = DateTime.Parse(w3Time);
Console.WriteLine(time);
// Taken from nytimes.com
string nyTime = "Thursday, February 26, 2009";
time = DateTime.Parse(nyTime);
Console.WriteLine(time);
// Taken from this site
string perlTime = "February 26, 2009";
time = DateTime.Parse(perlTime);
Console.WriteLine(time);
// Taken from ISO Standard 8601 for Dates
string isoTime = "2002-02-10";
time = DateTime.Parse(isoTime);
Console.WriteLine(time);
// Taken from Windows file system Created/Modified
string windowsTime = "2/21/2009 10:35 PM";//???????????????????????????????????
time = DateTime.Parse(windowsTime);
Console.WriteLine(time);
// Taken from Windows Date and Time panel
string windowsPanelTime = "8:04:00 PM";
time = DateTime.Parse(windowsPanelTime);
Console.WriteLine(time);
}
}
Loading

VulpesPosted Nov 19, 2014, 7:24 AM
I see from your profile that you're in Canada. Well, I'm in the UK and I get the same exception because here we write the day before the month.
I'd imagine that the site you linked to is in the US which, of course, does place the month before the day. You can mimic this behaviour as follows:
The output now is:
MahaPosted Nov 19, 2014, 7:40 AM
Manish Kumar ChoudharyPosted Nov 19, 2014, 7:08 AM
Hi Maha,
Actually the reason of this error is DateTime.Parse() is not able to identify the format of the string. Basically it read 21 as the month value so it's throwing that error.
To correct that error use following code
// Taken from Windows file system Created/Modified
string windowsTime = "2/21/2009 10:35 PM";//???????????????????????????????????
time = DateTime.ParseExact(windowsTime, "M/dd/yyyy hh:mm tt", CultureInfo.InvariantCulture);
Console.WriteLine(time);