简体   繁体   中英

Formatting Datetime2 in SQL Server

I am trying to format a datetime2 into yyyy-mm-dd hh:mm:ss format.

I have tried the below options:

This is throwing an error:

SELECT CONVERT(datetime2, 120); 

This works fine, but I need the output of type datetime2

SELECT CONVERT(VARCHAR(19), GETDATE(), 120);

How can I achieve this?

You are calling the CONVERT() function without specifying the data type to convert to, so in your case SELECT CONVERT(datetime2, 120); SQL Server will try to convert the value 120 to a datetime2 and that's why you get this error (which you don't provide)

Explicit conversion from data type int to datetime2 is not allowed.

To use CONVERT() with date and time styles, you need to pass

CONVERT(<datatype to convert to>, <Value to be converted>, <Style>) .

The SYSUTCDATETIME returns a datetime2 you can convert to as

SELECT CONVERT(VARCHAR(20), SYSUTCDATETIME(), 120)
--Change SYSUTCDATETIME() with your column/variable

For what you say

but I need the output of type datetime2

A DATETIME doesn't have a format, it's a binary value, thus you need to convert it to a formatted string. Since you need to return a DATETIME2 then you need to leave it as it is, and do the formatting in presentation layer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM