简体   繁体   English

转换SQL DateTime格式

[英]Convert SQL DateTime format

如何将DATETIME值( 2010-12-02 15:20:17.000 )显示为02/12-2010 15:20

对于SQL Server:

select stuff(convert(varchar, getdate(), 105), 3, 1, '/') + ' ' + left(convert(varchar, getdate(), 8), 5)

DateTime is a DateTime is a DateTime - it just holds a date and time and doesn't have any string representation, really. DateTimeDateTimeDateTime实际上,它只保存日期和时间,没有任何字符串表示形式。

See the CAST and CONVERT topic in the SQL Server Books Online for details - it shows all supported date formats that SQL Server supports. 有关详细信息,请参见SQL Server联机丛书中的CAST和CONVERT主题-它显示了SQL Server支持的所有受支持的日期格式。

For your source format ( 2010-12-02 15:20:17.000 ) you could probably use style no. 对于您的源格式( 2010-12-02 15:20:17.000 ),您可能会使用样式编号。 121 121

DECLARE @source VARCHAR(50)
SET @source = '2010-12-02 15:20:17.000'

DECLARE @Date DATETIME
SELECT @Date = CONVERT(DATETIME, @source, 121)

SELECT @Date

but your target format is a bit odd..... I don't see any "out of the box" style that would match your needs. 但是您的目标格式有点奇怪.....我看不到任何符合您需求的“开箱即用”样式。 You'll need to use some string manipulation code to get that exact format. 您将需要使用一些字符串操作代码来获取确切的格式。

Use MSSQL's build-in function to convert datetime to string with format, 使用MSSQL的内置函数将日期时间转换为具有格式的字符串,

SELECT CONVERT(VARCHAR(8), GETDATE(), 1) AS [MM/DD/YY] --2/5/12
SELECT CONVERT(VARCHAR(10), GETDATE(), 103) AS [DD/MM/YYYY] --5/2/2012

You need to create custom function to get various format to use like this; 您需要创建自定义函数来获得各种格式的使用,例如:

SELECT dbo.ufn_FormatDateTime(GETDATE(),'YYYY-MM-DD HH:mm:SS tt')
--Output : 2012-02-05 01:58:38 AM

SELECT dbo.ufn_FormatDateTime(GETDATE(),'(dddd) mmmm dd, yyyy hh:mm:ss.fff tt')
--Output : (Sunday) February 05, 2012 01:58:38.723 AM

SELECT dbo.ufn_FormatDateTime(GETDATE(),'dd/MM/yyyy')
--Output : 05/02/2012

SELECT dbo.ufn_FormatDateTime(GETDATE(),'yyyy MMM, dd (ddd) hh:mm:ss tt')
-- Output : 2012 Feb, 05 (Sun) 01:58:38 AM

Get the code snippet from this link. 从此链接获取代码片段。 http://www.tainyan.com/codesnippets/entry-62/sql-server-date-time-format-function.html http://www.tainyan.com/codesnippets/entry-62/sql-server-date-time-format-function.html

我在德国和瑞士使用的小例子:dd.mm.yyyy hh:mm

SELECT CONVERT(varchar, GETDATE(), 104) + ' ' + LEFT(CONVERT(varchar, GETDATE(), 108), 5)

Assuming Oracle: 假设Oracle:

select TO_CHAR(SYSDATE, "dd/mm-yyyy HH24:mi")
    from DUAL;

Assuming SQL Server: 假设SQL Server:

select STR(DATEPART(DAY, GETDATE()), 2) 
        + '/' 
        + STR(DATEPART(MONTH, GETDATE()), 2) 
        + '-' 
        + STR(DATEPART(YEAR, GETDATE()), 4) 
        + ' ' 
        + STR(DATEPART(HOUR, GETDATE()), 2) 
        + ':' 
        + STR(DATEPART(MINUTE, GETDATE()), 2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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