Over a million developers have joined DZone.

Extract And Pad Date Parts In SQL

DZone's Guide to

Extract And Pad Date Parts In SQL

Free Resource
Example T-SQL script to extract year, month, day, hour, minute, and second parts from a datetime, and pad them with leading zeros as needed. Useful for creating an ISO8601 date string.

-- Extract and pad parts of a datetime (also convert parts to strings)
declare @now datetime
set @now = getDate()
select datename(yyyy, @now) as year
  , right(N'0' + convert(nvarchar(2), month(@now)), 2) as month
  , right(N'0' + datename(d, @now), 2) as day
  , right(N'0' + datename(hh, @now), 2) as hour
  , right(N'0' + datename(n, @now), 2) as minute
  , right(N'0' + datename(s, @now), 2) as second

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}