Tarun
Tarun

Reputation: 221

Unexpected number of days between two dates

I am working on Windows 7 OS and calculating the number of days between two days using the code below:

DateTime dt = Convert.ToDateTime(txtNewIDDtAccRej.Text);
DateTime dtt = Convert.ToDateTime(txtNewIDDtInternal.Text);

TimeSpan t = dt - dtt;
txtNewProcessTime.Text = Convert.ToInt32(t.TotalDays).ToString();

This code is working fine on my system and values are coming like this as in below image:

Image1

In the above image, the time part is 00:00:00.

But the problem is after deploying the same code in test server which runs Windows Server 2003 R2, the difference between the two dates is coming wrong. Suppose the difference between 08-02-2012 and 07-02-2012 is 1 but on the test server it is 31. I am using exactly the same code.

Here is image for test server:

Image of Test Server

As per the image the time value is 12:00:00. What may be the cause of this?

Upvotes: 2

Views: 347

Answers (3)

Kamyar
Kamyar

Reputation: 18797

I think it's because of date formatting (localization). In your computer 08-02-2012 means February 8th (dd-MM-yyyy) and 07-02-2012 is February 7th hence the difference is one day. On server this is interpreted as August 2nd and July 2nd (MM-dd-yyyy). So the difference is 31 days.
Below is the snippet to solve the problem: (not tested)

 CultureInfo en = new CultureInfo("en-US");
 var format = "dd/MM/yyyy";
 DateTime myDate =  DateTime.ParseExact(myDateStr,format,en.DateTimeFormat);

Upvotes: 2

Amar Palsapure
Amar Palsapure

Reputation: 9680

Instead of doing Convert.ToDateTime use DateTime.TryParse with CultureInfo. The issue might be on the server Culture is different than your local machine.

OR

You can use DateTime.ParseExact. Here you can specify the date format also. Read more @ MSDN.

You can try this

string s = "08-02-2012";
string format ="dd-MM-yyyy";
//Get DateTime
DateTime dateTime = DateTime.ParseExact(s, format,new System.Globalization.CultureInfo("en-US"));
//Get string representation of DateTime
string date = dateTime.ToString(format, new System.Globalization.CultureInfo("en-US"));

This will work same on all machines.

Hope this solves your issue.

Upvotes: 2

Bruce
Bruce

Reputation: 187

The two systems are reporting the same time in different formats. Your system is reporting the time in 24 hour format (00:00:00) and the test server is using 12 hour format (12:00:00 AM). For calculation purposes, the dates are the same. If you require a specific format on output, use DateTime.Format().

Upvotes: 0

Related Questions