I'm surprised not to be able to find this question here already.
I have a date time var and I want to convert it to a string so that I can append it to another string. I want it in a format that can be converted easily back to a date time.
How can I do this?
(I want the date part and the time part.)
The following query will get the current datetime and convert into string. with the following format yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar(25), getdate(), 120)
I still can't get over the fact that you have to pass arbitrary numbers to get the right format
@cja I totally share your surprise. I want to provide a string, like yyddss to get the exact format I want. There's probably a technical or historical reason to this. But still - very surpriannoying.
Thanks for the quick fix but in your answer you are coding the months as minutes, yyyy-MM-dd hh:mm:ss NOT yyyy-mm-dd hh:mm:ss
Though this is old, I just ran into this thread. When using
DateTimeOffSet
, be sure to adjust thevarchar
length to what you want your outcome to look like. For me, I didn't want the timezone so I had to useSELECT convert(varchar(19), sysdatetimeoffset(), 120)