英文:
Compare 2 dates in string format in asp.net c#
问题
我尝试比较这两个以字符串格式表示的日期,但无法成功
{
SqlCommand cmd = new SqlCommand($"SELECT Last_Login_Date FROM [dbo].[Member] WHERE EmailAddress='{emailAddress}');");
SqlDataReader reader = cmd.ExecuteReader();
string lld = reader["Last_Login_Date"].ToString();
string currentDate = DateTime.Now.ToString();
if (DateTime.Parse(lld, currentDate))
}
英文:
I try to compare these 2 dates in string format but it couldnt work out
{
SqlCommand cmd =new SqlCommand($"SELECT Last_Login_Date FROM [dbo].[Member] WHERE EmailAddress='{emailAddress}');") ;
SqlDataReader reader = cmd.ExecuteReader();
string lld = reader["Last_Login_Date"].ToString();
string currentDate = DateTime.Now.ToString();if (DateTime.Parse(lld,currentDate))
}
答案1
得分: 1
Make sure data type of Last_Login_Date is datetime or date.
I'll use GetDateTime
to get value.
SQL Server
SqlDataReader.GetDateTime
MySQL MySqlDataReader.GetDateTime
like this reader.GetDateTime(reader.GetOrdinal("ColumnName"));
So you will change your string lld
to DateTime lld
ex: DateTime lld = reader.GetDateTime(reader.GetOrdinal("ColumnName"));
Then compare two variables DateTime.Compare(currentDate, lld)
.
Hope this helps!
英文:
Make sure data type of Last_Login_Date is datetime or date.
I'll use GetDateTime
to get value.
SQL Server
SqlDataReader.GetDateTime
MySQL MySqlDataReader.GetDateTime
like this reader.GetDateTime(reader.GetOrdinal("ColumnName"));
So you will change your string lld
to DateTime lld
ex:DateTime lld = reader.GetDateTime(reader.GetOrdinal("ColumnName"));
Then compare two variables DateTime.Compare(currentDate,lld)
.
Hope this help !
答案2
得分: 0
你不能在字符串上使用日期函数。从数据阅读器中读取日期并添加您的比较逻辑。
using (var conn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand($"SELECT Last_Login_Date FROM [dbo].[Member] WHERE EmailAddress='{emailAddress}';"))
{
DateTime lastlogindate;
cmd.Connection = conn;
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
lastlogindate = reader.GetDateTime("Last_Login_Date");
// 在这里添加您的比较逻辑
Console.WriteLine(DateTime.Compare(lastlogindate, DateTime.Now)); // 结果为 -1
}
}
英文:
You cannot use datefunctions on string. Read the date from datareader and add your comparision logic.
using (var conn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand($"SELECT Last_Login_Date FROM [dbo].[Member] WHERE EmailAddress='{emailAddress}';"))
{
DateTime lastlogindate;
cmd.Connection = conn;
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
lastlogindate = reader.GetDateTime("Last_Login_Date");
//add your comparision logic here
Console.WriteLine(DateTime.Compare(lastlogindate, DateTime.Now)); //result -1
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论