Date Time gives error after hosting

时间:2016-10-19 13:32:44

标签: c# .net sql-server datetime

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.

2 个答案:

答案 0 :(得分:3)

如果数据库中的日期以日期格式存储,那么您可以执行以下操作:

DateTime d1 = b.dr.GetDateTime(1).Date;
DateTime d2 = System.DateTime.Today;
TimeSpan ts = d2.Subtract(d1);

编辑:

如果字段以日期格式(如date,datetime,datetime2,smalldatetime等)存储在数据库中,则SqlDataReader.GetDateTime()方法将获取该值并将其转换为.Net DateTime值。当它们被表示为这些专用日期数据类型时,操作日期值通常更方便。

日期字符串的问题在于,有时这些可以有多种解释。然而,专门的日期格式各有特定且定义明确的解释。但是,如果您尝试将日期/时间值转换为字符串表示形式或从字符串表示形式转换,则可能会再次遇到格式问题。只要您可以避免此类转换,无论服务器中的日期时间设置如何,一切都会很好。

如果数据库中的字段没有时间组件(如果数据库数据类型是DATE而不是DATETIME),则可以省略第一行的.Date部分,并执行以下操作:

DateTime d1 = b.dr.GetDateTime(1);
DateTime d2 = System.DateTime.Today;
TimeSpan ts = d2.Subtract(d1);

答案 1 :(得分:0)

您的DB字段类型是什么? 假设它是datetime。目前还不清楚为什么要对它进行ToString()来立即解析字符串。 ParseExact正是这样做的。您正在寻找的格式应该完全匹配。它与您添加到字符串中的“:::: ...”格式不匹配。另外,ToString()使用的服务器上可能有不同的当前文化,因此您在ParseExact中请求的格式可能不匹配。