1

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))

}

4
  • 2
    Has this anything to do with the php tag? Commented Jan 6, 2020 at 7:53
  • what did you mean compare these 2 dates in string format ? what's wrong with converting them into DateTime and compare them ? Commented Jan 6, 2020 at 7:54
  • No. I'm using c# asp.net. I retrieve from sql server to get the last_login_date to compare to current_date. Both of the date are in string format so I don't know how to do the comparison Commented Jan 6, 2020 at 7:54
  • i tried to use DateTime.Compare(currentdate,last_login_date) and this error pops out (cannot convert from 'string' to 'System.DateTime') Commented Jan 6, 2020 at 7:56

2 Answers 2

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 help !

Sign up to request clarification or add additional context in comments.

Comments

0

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    
    }
}

2 Comments

i tried your code and this error pop out ExecuteReader: Connection property has not been initialized.
@HowToGame, you need to set the connection to SqlCommand. I have changed the code to include connection

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.