如何使用c#从sql server转换日期值?
我正在使用WinForms和C#,并试图比较数据库中的日期和当前日期 我的代码如下:如何使用c#从sql server转换日期值?,c#,.net,winforms,C#,.net,Winforms,我正在使用WinForms和C#,并试图比较数据库中的日期和当前日期 我的代码如下: DataManager.NotificationManager obj = new DataManager.NotificationManager(); DataTable dt1 = obj.GetListExpiryDate(); string currendate = DateTime.Today.ToString("yyyy-MM-dd"); foreach (DataRow ro
DataManager.NotificationManager obj = new DataManager.NotificationManager();
DataTable dt1 = obj.GetListExpiryDate();
string currendate = DateTime.Today.ToString("yyyy-MM-dd");
foreach (DataRow row in dt1.Rows)
{
if (DateTime.Parse(row.ItemArray[41].ToString("dd/MM/yyyy")) == currendate)
{
MessageBox.Show("Expired carte for the employee" + row["EmpFName"]);
} //.RowStyles[0].Height = 0; this.tlp_id.ColumnStyles[1].Width = 0; }
else
{
MessageBox.Show(" not Expired carte for the employee" + row["EmpFName"]);
}
}
问题是来自数据库的数据与currentdate
值的格式不同
有什么想法吗?不要在currentdate中将DateTime转换为字符串,而是将数据库返回的值转换为DateTime值并进行比较
DataManager.NotificationManager obj = new DataManager.NotificationManager();
DataTable dt1 = obj.GetListExpiryDate();
DateTime currendate = DateTime.Today;
foreach(DataRow row in dt1.Rows)
{
if (DateTime.Parse(row.ItemArray[41].ToString().Date) == currendate)
{
MessageBox.Show("Expired carte for the employee" + row["EmpFName"]);
}
else
{
MessageBox.Show(" not Expired carte for the employee"+row["EmpFName"]);
}
}
不要将来自数据库的日期格式化为字符串。相反,请将该值用作
DateTime
:
if (((DateTime)row.ItemArray[41]).Date == DateTime.Today) {
MessageBox.Show("Expired carte for the employee" + row["EmpFName"]);
}
这样,格式就变得无关紧要了
注意使用
.Date
和DateTime.Today
确保只比较日期部分,忽略时间部分。如果项目41确实是一个DateTime对象,最简单的方法是:
var dt = row[41] as DateTime;
if (dt != null) {
// process dt as a DateTime object.
}
在使用
DateTime
转换时,我建议使用TryParse()
;它允许您提供字符串数组作为可能的输入格式。
以下是最重载的签名:
public static DateTime ParseExact(
string s,
string[] formats,
IFormatProvider provider,
DateTimeStyles style
)
可能重复
DateTime.Parse()
以将您的值从数据库获取到DateTime
只是一个旁注:硬编码值(如41)从来不是一个好主意..因为我有一个包含多行的大表。我还能做什么呢?使用常量或枚举,这样,如果事情发生了变化,您只需在一个地方进行更改—更好的代码可维护性。