Wednesday, July 22, 2015

Formatting for 2 digits number: Month, Day, Hour, Minute

I have seen many ways of formatting a number related to month, day, hour, minute to two digits number. It is all about checking whether the given value has two digits, if not, add a leading zero for making it as two digit number. Some use IF statement, some use CASE statement and some use CONVERT and SUBSTRING. What is the best way? Based on the implementation require, you may use an appropriate one but I feel best way is, just add a leading zero without checking the length and then take right two digits as below;

DECLARE @GivenDate date = getdate();
DECLARE @GivenMonth1 int = 7;
DECLARE @GivenMonth2 int = 12;

SELECT RIGHT('0' + CONVERT(varchar(2), MONTH(@GivenDate)), 2) AS MonthOfGivenDateWithTwoDigits;
SELECT RIGHT('0' + CONVERT(varchar(2), @GivenMonth1), 2) AS MonthOfGivenMonthWithTwoDigits;
SELECT RIGHT('0' + CONVERT(varchar(2), @GivenMonth2), 2) AS MonthOfGivenMonthWithTwoDigits;


No comments: