?

Log in

Previous Entry | Next Entry

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?

Answer
Well first lets try to write question programmatically
String MyDateTimeString=”31/12/2012”;
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;
ObjPriDateTimeFormat.ShortDatePattern="yyyy/MM/dd";
current.DateTimeFormat = ObjPriDateTimeFormat;
Thread.CurrentThread.CurrentCulture = current;

Hope it helped

Want to learn C# step by step start from the below video

Copy right www.questpond.com

Buy 600+ Real Time Interview Videos

Call +91-22-66752917 or mail us on questpond@questpond.com for more details on C#, .NET, ASP.NET, SQL Server interview question videos.

SQL Server interview question videos

Latest Month

January 2017
S M T W T F S
1234567
891011121314
15161718192021
22232425262728
293031    

Tags

Powered by LiveJournal.com