Monday, March 19, 2012

DateTime Now Problem

Hey, basically i have a database of users and on a certain page load i want to register when they logged onto that page, so i created this snippet of code :

SqlCommand UpdateMyTime = new SqlCommand("UPDATE Users SET LastUpdated = '" + DateTime.Now + "' WHERE UserID = '" + CurrentUserID + "'", Connection);
UpdateMyTime.ExecuteNonQuery();


but that give me the error :

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
The statement has been terminated.

So I changed it to :

SqlCommand UpdateMyTime = new SqlCommand("UPDATE Users SET LastUpdated = '" + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + "' WHERE UserID = '" + CurrentUserID + "'", Connection);
UpdateMyTime.ExecuteNonQuery();

as when I looked at previous times in my database there format was "27/08/2007 15:25:45" for example. but that gives me the exact same error can anyone tell me why this doesnt work? / how to get it to work? My datatype for this feild is "datetime". Thanks John

SqlCommand UpdateMyTime = new SqlCommand("UPDATE Users SET LastUpdated= '" + DateTime.Now.ToString() + "' WHERE UserID = '" + CurrentUserID + "'",Connection);
UpdateMyTime.ExecuteNonQuery();

OR , best way is

SqlCommand UpdateMyTime = new SqlCommand("UPDATE Users SETLastUpdated= GetDate() WHERE UserID = '" + CurrentUserID + "'",Connection);
UpdateMyTime.ExecuteNonQuery();

|||

Awesome this :

SqlCommand UpdateMyTime = new SqlCommand("UPDATE Users SETLastUpdated= GetDate() WHERE UserID = '" + CurrentUserID + "'",Connection);
UpdateMyTime.ExecuteNonQuery();

way did work the best, for anyone else who is having this problem, thanks loads! John

No comments:

Post a Comment