EDIT: Forced to use 2008 R2
I need to get the two digit year to appended to an invoice number (for simplicity sake I am using a test variable). Previously I only needed the month and day appended but the customer is now asking for the two digit year.
My Method: REPLACE SUBSTRING STR YEAR(variable DATETIME)
REPLACE((SUBSTRING(STR (Year(@Date),4),3,2)), ' ', '0')**
My code:
DECLARE @TestVariable AS VARCHAR(100),
@Date as datetime = GetDate()
SET @TestVariable = '1234'
REPLACE(STR(MONTH(@Date), 2), ' ', '0')
REPLACE(STR(DAY(@Date), 2), ' ', '0')
REPLACE((SUBSTRING(STR (Year(@Date),4),3,2)), ' ', '0')
PRINT @TestVariable
CodePudding user response:
Honestly, just don't work with 2 digit years any more; learn the lessons of last century's mistake and use 4 digits.
If you "have" to, then you could use CONVERT
with a style code, and then just replace the characters with an empty string:
DECLARE @TestVariable varchar(100) = '1234',
@Date datetime = GETDATE();
SELECT @TestVariable REPLACE(CONVERT(varchar(8),@Date, 1),'/','');
CodePudding user response:
You can simplify the whole process, not just the year portion. Using FORMAT you can accomplish this easily.
DECLARE @TestVariable AS VARCHAR(100) = '1234'
, @Date as datetime = GetDate()
Select @TestVariable FORMAT(@Date, 'MMddyy')
CodePudding user response:
select replace(convert(varchar(20),@date,1)'/','') --or any other you need
See the docs
CodePudding user response:
I'll echo others' sentiment of "do you really have to use a two-digit year"? But if you have to, I like this sort of thing
set @TestVariable = '1234'
right('0' cast(month(@date) as varchar(2)), 2)
right('0' cast(day(@date) as varchar(2)), 2)
right('0' cast(year(@date) % 100 as varchar(2)), 2);
To talk through the general approach, I'm using right('0', «something», 2)
as a means to zero pad to two places, using cast(«something» as varchar(2))
to get a string instead of a number (so implicit conversion doesn't just add zero and the relevant datepart), and finally year(@date) % 100
to get the last two digits of the date.