The below c# date and time question is provided by www.questpond.com who provide c# interview question videos.
Let’s say I have a string variable with some date time value. When I try to convert string in to datetime using DateTime.Parse an exception getting popped up as follows.
“The string was not recognized as a valid DateTime”
Now tell me what may the reason for this? How will we solve it?
Well first lets try to write question programmatically
DateTime MyDateTime=DateTime.Parse(MyDateTimeString); //This line will later throw an exception”.
Reason for this kind of error is ‘Current culture’s DateTime Format”.
By Default every application considers hosting machines configure format as its(application’s datetime format). That’s why at some places we get this kind of error because string is in “dd/MM/yyyy” format and machines format may be something else.(Lets say it is yyy/MM/dd).
Solution for this kind of problem is
1) Use DateTime constructor andmanually provide every part as
DateTime MyDateTime=new DateTime(MyYear,MyMonth,MyDate);
2)Change System Applications Current DateTime Format to yur desired one as follows.
CultureInfo current = Thread.CurrentThread.CurrentCulture.Clone() as CultureInfo;
DateTimeFormatInfo ObjPriDateTimeFormat = DateTimeFormatInfo.CurrentInfo.Clone() as DateTimeFormatInfo;
current.DateTimeFormat = ObjPriDateTimeFormat;
Thread.CurrentThread.CurrentCulture = current;
Hope it helped
Want to learn C# step by step start from the below video