Over a million developers have joined DZone.

Extract And Pad Date Parts In SQL

·
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
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}