How to convert date format from 05-JUN-99 to 050599? - sql

I have gone through the suggested date formats here but didn't find any that meets my requirement.
I have the following date format:
05-JUN-99. 05 being dd as in day, JUN and the year 1999.
I have been asked to convert that to mmddyy (two digit month, two digit day and two digit year).
Any ideas how to do this?
Thanks for your assistance

You can use convert here.
select convert(varchar(20),cast('05-JUN-99' as date),10)
--Output: 06-05-99
select replace(convert(varchar(20),cast('05-JUN-99' as date),10),'-','')
--Output: 060599
Date Styles from the documentation

My Vote use FORMAT for SQL-SERVER 2012 +
SELECT FORMAT(CAST('05-JUN-99' AS DATETIME),'MMddyy')
This means no nested replaces, no extraneous cast/converts etc. keeps it tidier IMHO

I usually just convert to string. Get the year, month, day, put them each in a string and concatinate them.
Declare #InputValue Varchar(16) = '05-JUN-99'
set #InputValue = replace(#InputValue,'-','/')
declare #TestDate DateTime
set #TestDate = convert(DateTime,#InputValue)
select #TestDate
select right ('0' + convert(Varchar(2),DATEPART(mm,#TestDate)),2)
+ right ('0' + convert(Varchar(2),DATEPART(dd,#TestDate)),2)
+ right ('0' + convert(Varchar(4),DATEPART(yy,#TestDate)),2)

Related

How to subtract one month from a date using SQL Server

I have a date in format dd/mm/yyyy. I want to subtract one month from it.
I am using this code but the output is "09/10/2020" I don't know why my code does the subtraction of the year -2 also.
This is my request
SELECT
FORMAT(CONVERT (DATE, DATEADD(MONTH, -1, CONVERT(char(9), GETDATE()))), 'dd/MM/yyyy')
you need to change it to:
select format(CONVERT (date,DATEADD(MONTH, -1,GETDATE())), 'dd/MM/yyyy' )
but as Larnu stated. it seems like you need to change the column.
Your current code doesn't work as expected because:
SELECT CONVERT(char(9), GETDATE());
Returns this (at least in my language):
Nov 9 20
Which is, unfortunately, and again in my language, a valid date (but in {20}20, not {20}22).
Even in the right style (103), char(9) would yield 10/11/202 tomorrow, since 9 digits is only enough if either the day or month is a single digit.
Don't know why you are converting GETDATE() to a string. Just perform date math on it and then format it if you need to (using a specific style number, e.g. 103 for d/m/y):
SELECT CONVERT(char(10), DATEADD(MONTH, -1, GETDATE()), 103);
I really wouldn't use FORMAT() for such simple output, as the CLR overhead really isn't worth it. Ideally you leave it as a date/time type until presentation time - surely your presentation layer can present your date as d/m/y if that's really a wise idea.
And if you are storing or passing dates as strings (and worse, in regional formats like d/m/y) you really should consider fixing that.
First of all,
You should be storing your Date as a string for easier manipulation. If you don't want to change the column, you can always convert from Date to Varchar and then (re)convert it.
Example:
First, convert Date to varchar using the style code '112' ISO for formatting as yyyyMMdd:
DECLARE #date DATE = GETDATE();
DECLARE #dateConverted as VARCHAR (8) = (SELECT CONVERT(VARCHAR, #date, 112));
Then you just subtract the month using DATEADD():
DECLARE #previousMonth AS VARCHAR (8) = (SELECT FORMAT(DATEADD(month, -1, #dateConverted), 'yyyyMMdd'));
Finally, convert varchar do Date again:
DECLARE #previousMonthConverted AS DATE = (SELECT CONVERT(CHAR(10), CONVERT(date, #previousMonth), 120));

Looking to replace the year in SQL Server

I am converting a date using CONVERT(varchar,DateOfBirth,101) for birthdates.
I want to show these dates with the current year, I've tried REPLACE but you can't use wildcards with it and when I use DATEPART, it doesn't format with the right digits for month and day. I also can't add years because they are wildly different birthdates. Thanks.
If you want to display the date as a string in 101 format for current year, one option uses a direct format():
format(DateOfBirth, 'MM/dd/2020')
You can compute the current date dynamically:
format(DateOfBirth, concat('MM/dd/', year(getdate())))
On the other hand, if you want your result as a date, then you could use datefromparts():
datefromparts(year(getdate()), month(DateOfBirth), day(DateOfBirth))
If it is a datevalue, you can use FORMAT function. If it is a character value, you can use RIGHT and REPLACE.
DECLARE #dateValue DATETIME = '05/12/1999'
DECLARE #dateCharValue VARCHAR(12) = '05/12/1999'
SELECT FORMAT(#dateValue, 'MM/dd/2020')
SELECT REPLACE(#dateCharValue, RIGHT(#dateCharValue,4),2020)
--Result
05/12/2020
This could helped you:
The code CONVERT(varchar(5),GETDATE(),1) return this 05/27 and then just add the year of the date
SELECT CONVERT(varchar(5),GETDATE(),1) + '/' + cast(year(getdate()) as varchar)
Or
SELECT CONVERT(varchar(5),GETDATE(),1) + '/' + convert(varchar,year(getdate()))
The result of both:
05/27/2020 --(This is my current date n.n )
This work but if you use a string something like your example DateOfBirth will be the variable and if this is a string (DateOfBirth = '5/27/1987') you need to convert the string DateOfBirth to Date:
SELECT CONVERT(varchar(5),convert(date,DateOfBirth),1) + '/' + cast(year(GETDATE()) as varchar)
Or
SELECT CONVERT(varchar(5),convert(date,DateOfBirth),1) + '/' + convert(varchar,year(GETDATE()))
The Result of Both :
05/27/2020

Hardcode a specific day in data time while pulling the data - SQL

Actually I have different date in SQL table when I pull those via SQL query, day of datetime field should have fixed day.
Example: (DD-MM-YYYY) day should be "7" > (7-MM-YYYY)
10-08-2007 > 07-08-2007
27-12-2013 > 07-12-2013
01-03-2017 > 07-03-2017
Can someone help me on this. Thanks in Advance.
Find the difference between 7 and the day of the original date and add that to the original date:
SELECT DATEADD(DAY, 7 - DAY(OriginalDate), OriginalDate)
Use DATEPART to take out the month and year parts. Cast those into varchar and concatenate with 07.
Query
select '07-' +
cast(DATEPART(mm, [date_column]) as varchar(2)) + '-' +
cast(DATEPART(yyyy, [date_column]) as varchar(4))
from your_table_name;
Assuming You might have to change the day number example
DECLARE #dayNum char(2)
SELECT #dayNum = '07'
select #dayNum + Right(convert(char(10),getdate(),105),8)
If that is not the case You could do this
select '07'+ Right(convert(char(10),'10-08-2007',105),8)
I'd go this way:
SELECT CONVERT(DATE,CONVERT(VARCHAR(6),GETDATE(),112)+'25',112);
CONVERT with format 112 will return the date as unseparated ISO (today we would get 20170407). Convert this to VARCHAR(6) will implicitly cut away the day's part (201704).
Now we add a day and use again CONVERT with 112, but now with DATE as target type.
One thing to keep in mind: The day you add must be two-digit. You can achieve this with
DECLARE #int INT=7;
SELECT REPLACE(STR(#int,2),' ','0');
Use DATEFROMPARTS: Updated ONLY works from 2012 - OP has tagged SQL-Server 2008
select DATEFROMPARTS ( year('10-08-2007'), month('10-08-2007'), 7 )
Assuming that your field is of datetime datatype and your fixed day is of integer type.
select datetimecolumn+(yourparamfixedday-datepart(dd,datetimecolumn))

Elegantly convert DateTime type to a string formatted "dd-mmm"

We have the following solution:
select
substring(convert(varchar(20),convert(datetime,getdate())),5,2)
+ ' ' +
left(convert(varchar(20),convert(datetime,getdate())),3)
What is the elegant way of achieving this format?
You can do it this way:
declare #date as date = getdate()
select replace(convert(varchar(6), #date, 6), ' ', '-')
-- returns '11-Apr'
Format 6 is dd mon yy and you take the first 6 characters by converting to varchar(6). You just need to replace space with dash at the end.
You can use the dateName function:
select right(N'0' + dateName(DD, getDate()), 2) + N'-' + dateName(M, getDate())
If you really want the mmm part to only have the tree-letter abbreviation of the month, you're stuck with parsing the appropriate conversion type, for example
select left(convert(nvarchar, getDate(), 7), 3)
The problem is that dateName doesn't have an option to get you the abbreviated month, and the abbreviation isn't always just the first three letters (for example, in czech, two months start with Čer). On the other hand, convert 7 always starts with the abbreviation. Now, even with this, I assume that the abbreviation is always three letters long, so it isn't necessarily 100% reliable (you could search for space instead), but I'm not aware of any better option in MS SQL.
DECLARE #t datetime = getdate()
SELECT CONVERT(VARCHAR(24),LEFT(#t,6),113)
Try this...
SELECT LEFT(CONVERT(NVARCHAR(10), GETDATE(), 6), 6)

SQL Converting string MMM.YY to date

how do i convert/cast a column contains strings e.g. Jan.08,Feb.08.. into date format so that i can sort them?
Greatest Thanks!
I'd just format as a convertible string for the first of the relevant month, and then cast to datetime, e.g.
CAST('1.' + YourMonthAndYearColumnName AS DATETIME)
...is an expression that will yield a datetime that should be sortable, so:
SELECT
YourMonthAndYearColumnName
FROM
YourTable
ORDER BY
CAST('1.' + YourMonthAndYearColumnName AS DATETIME)
...should do what you're looking for.
If you can make the assumption that all dates will be within the last ten years, you can use the following code:
select convert(datetime, replace('Jan.08', '.', ' 20'))
select convert(datetime, replace('Dec.08', '.', ' 20'))
That formats the string into the format "Jan 2008", which is unambiguous. "Dec.08" could be "8th December this year" or "The month of december 2008".
Or you could use Matt Gibson's suggestion of prepending a "1." to your date before conversion. That removes the ambiguity, and has the advantage of using whatever defaults that SQL server has for dates (i.e. 50 is 1950 and 49 is 2049).
select convert(datetime, '1.' + 'Jan.08')
select convert(datetime, '1.' + 'Dec.49')
select convert(datetime, '1.' + 'Jan.50')