Reputation: 411
In my C# project I need system date time to another specific date time format.
My system datetime format is like "15/03/2017 9:25 AM"
--->that can be changed according to computer which my program run.
But I need to parse that datetime format to another date time format something like "2017-03-15 9:25 AM"----> save date in SQL database accept this format only.
I need Assign this to variable to Datetime Variable not need save in String variable.
I tried this code but not working
string datetimesss = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")
It returns
// value of datetimesss="2017-03-15 09:33:25"
Then I parse again to date time format
DateTime dates = DateTime.Parse(datetimesss);
It returns
// value of dates ="15/03/2017 9:42:43 AM"
Convert back to my computer datetime format. How can I convert any datetime format to DateTime "yyyy-MM-dd hh:mm:ss"
?
Thank You!
Upvotes: 0
Views: 2195
Reputation: 239824
You should avoid strings and just keep your data in DateTime
variables. ADO.Net already knows how to translate between .NETs DateTime
and SQL Server's datetime
- and neither of these has a format (both of them, internally, are just numbers. .NETs DateTime
is a count of 100ns intervals since 01/01/0001. SQL Server's datetime is a count of whole and fractional days since 01/01/1900).
Something like:
var updateCommand = new SqlCommand(
"UPDATE [User] SET Last_loign_date =@LastLoginDate"
,conn); //Assume conn is an SqlConnection object
updateCommand.Parameters.Add("@LastLoginDate",SqlDbType.DateTime).Value = DateTime.Now
or, in the alternative, why not use the database server time rather than passing it:
string sqlupdatepassword = "UPDATE [User] SET Last_loign_date =current_timestamp";
Upvotes: 2
Reputation: 411
Finaly I got the point, I parse DateTime to String
string sqlupdatepassword = "UPDATE [User] SET Last_loign_date ='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss tt") + "'";
In SQl database "Last_loign_date" is datetime format. this may not correct, but this worked for me.
thanks!
Upvotes: 0
Reputation: 1304
If sql server language is set as us-english then your date - > '15/03/2017 9:25 AM' will be considered as text and converting into date will not give correct results. You need create date based on day,month and year from your given date by using string functions. Use the below code to get required output :
declare @date varchar(30) = '15/03/2017 9:25 AM'
select cast(left(parsename(replace(@date,'/','.'),1),4) +
parsename(replace(@date,'/','.'),2) +
parsename(replace(@date,'/','.'),3) as datetime) +
ltrim(stuff(parsename(replace(@date,'/','.'),1),1,4,''))
Upvotes: 1