ITSagar ITSagar - 1 year ago 75
C# Question

Date Time gives error after hosting

I have a column in MSSQL DB Which has stored following date:

2016-06-10 10:55:00.000

I am calling this column on frontend using datareader, then parsing it to a specific format and then comparing with other date to find timestamp.
Issue is when I run it from Visual Studio, it works fine. but when I upload it on live server, I get the following exception:

6/10/2016 10:55:00 AM ::: d1 ::: :: System.FormatException: String was
not recognized as a valid DateTime. at
System.DateTimeParse.ParseExact(String s, String format,
DateTimeFormatInfo dtfi, DateTimeStyles style) at
login.btn_login_Click(Object sender, EventArgs e)

Following is my code:

tst = b.dr.GetValue(1).ToString() + " ::: d1 ::: ";
DateTime d1 = DateTime.ParseExact(b.dr.GetValue(1).ToString(), "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
tst = "d2";
DateTime d2 = DateTime.ParseExact(System.DateTime.Now.ToString(), "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
tst = "d3";
TimeSpan ts = d2.Subtract(d1);
tst = "d4";

I have also tried:

DateTime d1 = DateTime.ParseExact(b.dr.GetValue(1).ToString(), "dd-MM-yyyy", null);

Still it doesnot work on live server.
Also tried:

DateTime d1 = DateTime.ParseExact(b.dr.GetValue(1).ToString(), "dd-MM-yyyy HH:mm:ss", null);
DateTime d2 = DateTime.ParseExact(System.DateTime.Now.ToString(), "dd-MM-yyyy HH:mm:ss", null);

But no wonders.
Being a live server, it needs to be completely independent of the system culture and should work same along all the date time formats opted by the clients in their operating systems.

Note: On development end, I am using MSSQL R2 2008 Express while live server uses MSSQL 2012.

Answer Source

If the date in the database is stored in a date format, then you may be able to do as follows:

DateTime d1 = b.dr.GetDateTime(1).Date;
DateTime d2 = System.DateTime.Today;
TimeSpan ts = d2.Subtract(d1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download