Get 2 Digit Number For The Month - sql

I have an integer column "Month"
I would like to get 2 digit number for month.
This is what I have tried: DATEPART(mm, #Date)
It returns one digit for months January to September
I am using SQL Server 2008
Anyone has suggestion?

Function
FORMAT(date,'MM')
will do the job with two digit.

there are different ways of doing it
Using RTRIM and specifing the range:
like
SELECT RIGHT('0' + RTRIM(MONTH('12-31-2012')), 2);
Using Substring to just extract the month part after converting the date into text
like
SELECT SUBSTRING(CONVERT(nvarchar(6),getdate(), 112),5,2)
see Fiddle
There may be other ways to get this.

Pinal Dave has a nice article with some examples on how to add trailing 0s to SQL numbers.
One way is using the RIGHT function, which would make the statement something like the following:
SELECT RIGHT('00' + CAST(DATEPART(mm, #date) AS varchar(2)), 2)

Another simple trick:
SELECT CONVERT(char(2), cast('2015-01-01' as datetime), 101) -- month with 2 digits
SELECT CONVERT(char(6), cast('2015-01-01' as datetime), 112) -- year (yyyy) and month (mm)
Outputs:
01
201501

CONVERT(char(2), getdate(), 101)

Alternative to DATEPART
SELECT LEFT(CONVERT(CHAR(20), GETDATE(), 101), 2)
SQLFiddle Demo

append 0 before it by checking if the value falls between 1 and 9 by first casting it to varchar
select case when DATEPART(month, getdate()) between 1 and 9
then '0' else '' end + cast(DATEPART(month, getdate()) as varchar(2))

For me the quickest solution was
DATE_FORMAT(CURDATE(),'%m')

Simply can be used:
SELECT RIGHT('0' + CAST(MONTH(#Date) AS NVARCHAR(2)), 2)

Try:
select right ('0'+convert(nvarchar(2), DATEPART(mm, getdate())),2 )

My way of doing it is:
right('0'+right(datepart(month,[StartDate]),2),2)
The reason for the internal 'right' function is to prevent SQL from doing it as math add - which will leave us with one digit again.

SELECT REPLACE(CONVERT(varchar, MONTH(GetDate()) * 0.01), '0.', '')

Related

Subtracting Datetimes

I'm trying to find the most simple way to subtract to DATETIMEs from each other to produce a difference in the format of YY:MM.
Concatenating DATEDIFF of the two periods by year and month clearly just combines the same time differences together so a time period that is 2 years apart shows 2yrs,24months, when I am hoping to get it to show 2yrs,0months.
DATEDIFF(y,startdate,GETDATE())
Any tips? Thanks! Using SQL Server.
You can do this by constructing it with CONCAT() using the DATEDIFF() results by the month:
Select Concat
(
Right('00' + Convert(Varchar, DateDiff(Month, StartDate, GetDate()) / 12), 2),
':',
Right('00' + Convert(Varchar, DateDiff(Month, StartDate, GetDate()) % 12), 2)
)
Select Concat(DateDiff(YY,StartDate,GetDate()),' Yrs,')+Concat((DateDiff(MM,StartDate,GetDate())) % 12,' months')
Returns
2 Yrs,2 months
-- Assuming StartDate is 2014-04-29

how to Select getdate () in yyyy/M format

I want to select getdate() in the format yyyy/M. I tried to write a query
SELECT FORMAT(GETDATE(), 'yyyy/M')
but it is throwing an error.
I am a beginner in SQL. How do I get the yyyy/m format if there is only single digit month? E.g. the query should return 2016/1 when there is only one digit month (it should not return 2016/01) and should return 2016/10 when the month has two digits
How about getting the YEAR and MONTH part of the date and just concatenate them:
SELECT
CAST(DATEPART(YEAR, GETDATE()) AS VARCHAR(4)) + '/' +
CAST(DATEPART(MONTH, GETDATE()) AS VARCHAR(2))
Try this:
SELECT FORMAT(GETDATE(),'yyyy/MM')
SELECT FORMAT(CAST('2015-11-15' AS smalldatetime),'yyyy/M'),
FORMAT(CAST('2015-01-15' AS smalldatetime),'yyyy/M')
Gives:
2015/11 | 2015/1
SELECT CONVERT(VARCHAR(7), GETDATE(), 111) AS [YYYY/MM]
OR
SELECT CONVERT(VARCHAR(7), GETDATE(), 111)

Getting Month and Day from a date

It is possible simplify this query (MSSQL)?
SELECT RIGHT(STR(MONTH('2014-05-02'))+100,2) + '-'
+ RIGHT(STR(DAY('2014-05-02'))+100,2)
I want month and day from a date but always with leading zeros if only have one digit in the month / day. In this date 2014-05-02 I want only 05-02. I can do that with this query but I don't know if there is a simply way...
SELECT CONVERT(CHAR(5), GETDATE(), 10)
Result:
05-23
Please try:
select RIGHT(CONVERT(nvarchar(10), GETDATE(), 126), 5)
For the example,
select RIGHT(CONVERT(nvarchar(10),CONVERT(DATETIME, '2014-5-2'), 126), 5)
Try this...
SELECT LEFT(CONVERT(VARCHAR(10), GETDATE(), 110),5)
OR
SELECT LEFT(CONVERT(VARCHAR(8), GETDATE(), 10),5)
Both return the same result as follows
RESULT: 05-23
I like using format.
If you have a string:
select format(convert(date, '2014-05-23', 126),'MM-dd');
If you have a date:
select format(GetDate(),'MM-dd');
This could really Help you.
DECLARE #A DATETIME = GETDATE()
SELECT CONVERT(VARCHAR(5),#A,110)

How can I get the month number (not month name) from a date in SQL Server?

How can I get the month number in sql? I use the following code but it returns the month name.
SELECT DATENAME(mm, GETDATE())
Use datepart function with m extension.
SELECT DATEPART(m, getdate())
Use the month function - SELECT MONTH(GETDATE())
Use Datepart:
DATEPART(mm,getdate());
You want DATEPART:
select datepart(mm, getdate())
You can also use this to pad the month number
SELECT RIGHT('00' + RTRIM( CAST( DATEPART( MONTH, GETDATE() ) AS varchar(2)) ) , 2)
Try the below:
SELECT DATEPART(mm,getdate())
This will return with two char in case of Jan-Sep:
SELECT CASE WHEN LEN(MONTH(GETDATE())) = 1 THEN '0' + CAST(MONTH(GETDATE()) AS VARCHAR(2))
WHEN LEN(MONTH(GETDATE())) = 2 THEN CAST(MONTH(GETDATE()) AS VARCHAR(2)) END
We can use the SQL Function: MONTH(DATE) as a parameter. It will return the month number.

How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09)

DECLARE #day CHAR(2)
SET #day = DATEPART(DAY, GETDATE())
PRINT #day
If today was the 9th of December, the above would print "9".
I want to print "09". How do I go about doing this?
Pad it with 00 and take the right 2:
DECLARE #day CHAR(2)
SET #day = RIGHT('00' + CONVERT(NVARCHAR(2), DATEPART(DAY, GETDATE())), 2)
print #day
For SQL Server 2012 and up , with leading zeroes:
SELECT FORMAT(GETDATE(),'MM')
without:
SELECT MONTH(GETDATE())
Use SQL Server's date styles to pre-format your date values.
SELECT
CONVERT(varchar(2), GETDATE(), 101) AS monthLeadingZero -- Date Style 101 = mm/dd/yyyy
,CONVERT(varchar(2), GETDATE(), 103) AS dayLeadingZero -- Date Style 103 = dd/mm/yyyy
Try this :
SELECT CONVERT(varchar(2), GETDATE(), 101)
Leading 0 day
SELECT FORMAT(GetDate(), 'dd')
SQL Server 2012+ (for both month and day):
SELECT FORMAT(GetDate(),'MMdd')
If you decide you want the year too, use:
SELECT FORMAT(GetDate(),'yyyyMMdd')
Select Replicate('0',2 - DataLength(Convert(VarChar(2),DatePart(DAY, GetDate()))) + Convert(VarChar(2),DatePart(DAY, GetDate())
Far neater, he says after removing tongue from cheek.
Usually when you have to start doing this sort of thing in SQL, you need switch from can I, to should I.
SELECT RIGHT('0'
+ CONVERT(VARCHAR(2), Month( column_name )), 2)
FROM table
Might I suggest this user defined function if this what you are going for:
CREATE FUNCTION dbo.date_code (#my_date date) RETURNS INT
BEGIN;
DECLARE #retval int;
SELECT #retval = CAST(CAST(datepart(year,#my_date) AS nvarchar(4))
+ CONVERT(CHAR(2),#my_date, 101)
+ CONVERT(CHAR(2),#my_date, 103) AS int);
RETURN #retval;
END
go
To call it:
SELECT dbo.date_code(getdate())
It returns as of today
20211129
Roll your own method
This is a generic approach for left padding anything. The concept is to use REPLICATE to create a version which is nothing but the padded value. Then concatenate it with the actual value, using a isnull/coalesce call if the data is NULLable. You now have a string that is double the target size to exactly the target length or somewhere in between. Now simply sheer off the N right-most characters and you have a left padded string.
SELECT RIGHT(REPLICATE('0', 2) + CAST(DATEPART(DAY, '2012-12-09') AS varchar(2)), 2) AS leftpadded_day
Go native
The CONVERT function offers various methods for obtaining pre-formatted dates. Format 103 specifies dd which means leading zero preserved so all that one needs to do is slice out the first 2 characters.
SELECT CONVERT(char(2), CAST('2012-12-09' AS datetime), 103) AS convert_day
DECLARE #day CHAR(2)
SET #day = right('0'+ cast(day(getdate())as nvarchar(2)),2)
print #day
use
CONVERT(CHAR(2), DATE_COLUMN, 101)
to get the month part with 2 characters and
CONVERT(CHAR(2), DATE_COLUMN, 103)
for the day part.
Declare #dateToGet varchar(10)
Set #dateToGet = convert(varchar, getdate(), 112)
This works fine for the whole date with leading zeros in month and day
select
right('0000' + cast(datepart(year, GETDATE()) as varchar(4)), 4) + '-'+ +
right('00' + cast(datepart(month, GETDATE()) as varchar(2)), 2) + '-'+ +
right('00' + cast(datepart(day, getdate()) as varchar(2)), 2) as YearMonthDay