HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlModerate

SQL Server dates - can I get date and hour?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
cansqldatesandhourdategetserver

Problem

In SQL Server, can I do the equivalent of to_char(date_field, 'YYYY-MM-DD:HH24') in Oracle to get 2012-01-30:23?

Solution

In SQL Server <= 2012 you can say:

SELECT CONVERT(CHAR(10), date_field, 120) 
  + ':' + RIGHT('0' + CONVERT(VARCHAR(2), DATEPART(HOUR, date_field)), 2)
  FROM dbo.table ...;


Or

SELECT STUFF(CONVERT(CHAR(13), date_field, 120), 11, 1, ':')
  FROM dbo.table ...;


In SQL Server 2012 this is much easier; you can say:

SELECT FORMAT(date_field, 'yyyy-MM-dd:HH')
  FROM dbo.table ...;


Though FORMAT is considerably slower, so if you are doing this at scale, it isn't the one I would use (and in fact I would highly recommend you consider formatting your date output at the presentation layer, not in SQL Server).

SQL fiddle: http://sqlfiddle.com/#!6/72276/5

Code Snippets

SELECT CONVERT(CHAR(10), date_field, 120) 
  + ':' + RIGHT('0' + CONVERT(VARCHAR(2), DATEPART(HOUR, date_field)), 2)
  FROM dbo.table ...;
SELECT STUFF(CONVERT(CHAR(13), date_field, 120), 11, 1, ':')
  FROM dbo.table ...;
SELECT FORMAT(date_field, 'yyyy-MM-dd:HH')
  FROM dbo.table ...;

Context

StackExchange Database Administrators Q#20028, answer score: 10

Revisions (0)

No revisions yet.