Click below for Step by Step and Interview Q & A (dotnetinter) wrote,
Click below for Step by Step and Interview Q & A

C# date and time interview question with answers

The below c# date and time question is provided by 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
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;
current.DateTimeFormat = ObjPriDateTimeFormat;
Thread.CurrentThread.CurrentCulture = current;

Hope it helped

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

Tags: .net interview questions, c# date and time interview question, csharp interview questions, it interview questions with answers, programming interview questions

Recent Posts from This Journal

  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded