[英]How to convert the date value taken from the date time picker to the Date column in SQL Server table in Visual C#?
[英]How to convert a date value from sql server with c#?
我正在使用WinForms和C#,并且试图在数据库中的日期和当前日期之间进行比较。
我的代码如下:
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
值的格式不同!
有什么想法吗?
不要将来自数据库的日期格式化为字符串。 而是使用该值作为DateTime
:
if (((DateTime)row.ItemArray[41]).Date == DateTime.Today) {
MessageBox.Show("Expired carte for the employee" + row["EmpFName"]);
}
这种格式将变得无关紧要。
请注意使用.Date
和DateTime.Today
以确保仅比较日期部分,而忽略时间部分。
不用将DateTime转换为currentdate中的字符串,而是将数据库的返回值转换为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"]);
}
}
如果Item 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
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.