DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Jason has posted 22 posts at DZone. View Full User Profile

Extract And Pad Date Parts In SQL

10.30.2008
| 8605 views |
  • submit to reddit
        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