Extract And Pad Date Parts In SQL
Join the DZone community and get the full member experience.Join For Free
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.