I have a string date in database. I did like below mentioned format but it shows error like
input string was not in a correct format
But when I referred with internet this method is correct but it does not work for me. Let me know the reason?
string str1 = "select todate from Employee where EmpCode='" + code + "'";
SqlDataReader dr1 = conn.query(str1);
if (dr1.Read())
{
string todate1 = dr1[0].ToString();
int todate2 =Convert.ToInt32(todate1);
}
It sounds like you should be using a DateTime
column in the database, at which point there's no need for integers or strings:
var today = DateTime.Today; // Or maybe use DateTime.Now
// Use parameterized SQL rather than string concatenations
string sql = "select todate from Employee where EmpCode=@EmpCode";
using (var conn = new SqlConnection(...))
{
conn.Open();
using (var command = new SqlCommand(sql, conn))
{
command.Parameters.Add("@EmpCode", SqlDbType.VarChar).Value = code;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
DateTime date = reader.GetDateTime(0);
if (today > date)
{
// Do something
}
}
}
}
}
If your date really is being stored as a string and you can't change that (and if you can, then definitely do so), you can use DateTime.ParseExact
instead:
// Other code as before
while (reader.Read())
{
DateTime date = DateTime.ParseExact(reader.GetString(0),
"yyyy-MM-dd", // Or whatever the format is
CultureInfo.InvariantCulture);
if (today > date)
{
// Do something
}
}
Note that in both cases, this uses the system local time zone. You may want to consider storing all values in UTC, and performing all calculations that was as well - in which case you can use DateTime.UtcNow
.
See more on this question at Stackoverflow