Convert CMMDDYY into date in SQL Server - sql

If I have a date string in the format of CMMDDYY
C = 0, 1 or 2 where 0 represents 19, 1 represents 20 and 2 represents 21
Example:
1022511 would be 02/25/2011 in mm/dd/yyyy format.
Is there a way to convert this into mm/dd/yyyy format in sql server?
Is CMMDDYY even a valid date format? I haven't found much information on it.

The Year algorithm is simply: (19 + int(C))*100 + int(yy)
Try this:
declare #st nvarchar(7)
set #st = '1030609'
select
cast(
substring(#st,2,2) + '/'
+ substring(#st,4,2) + '/'
+ cast((19 + cast(substring(#st,1,1) as int) )* 100
+ cast(substring(#st,6,2) as int) as nvarchar)
as datetime)
This outputs:

It doesn't sound like a built in date format but you should be able to find it on msdn if it is. If not you could write a function in SQL server that parses a string in that format to a DateTime object

Related

Convert day + time string to time

I want to convert a column containing day hour minute and second to time (01 03:08:09) in SQL Server 2014 because it is in the nvarchar(255) data type, so that I can use the DATEDIFF function and I get an error message:
Conversion failed when converting date and/or time from character string.
I tried using;
SELECT CAST (Driver_at_restaurant_datetime AS time)
FROM deliveries
How do I resolve this?
01 03:08:09 is not a valid time, so it will produce an error. You need to extract 03:08:09 first with right() then convert it to a time as follows:
SELECT CAST (right(Driver_at_restaurant_datetime,8) AS time(0))
FROM deliveries
CONVERT(DATETIME,'1900-01-' + CONVERT(CHAR(2),CAST (LEFT(Driver_at_restaurant,2) AS INT) + 1) + RIGHT(Driver_at_restaurant,9),120)
This will convert your string to datetime and will let you apply datediff without loosing the "days" part.
The above implements ODBC cannonical style for convertion. More here:
https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16
EDIT
Here's a more comprehensive example:
declare #testString1 nvarchar(30) = '00 17:47:12';
declare #testString2 nvarchar(30) = '01 03:08:09';
declare #testDate1 Datetime = CONVERT(DATETIME,'1900-01-' + CONVERT(CHAR(2),CAST (LEFT(#testString1,2) AS INT) + 1) + RIGHT(#testString1,9),120)
declare #testDate2 Datetime = CONVERT(DATETIME,'1900-01-' + CONVERT(CHAR(2),CAST (LEFT(#testString2,2) AS INT) + 1) + RIGHT(#testString2,9),120)
SELECT
#testDate1 AS TestDate1,
#testDate2 AS TestDate1,
DATEDIFF(MINUTE,#testDate1,#testDate2) AS DateDiff_Minutes,
DATEDIFF(HOUR,#testDate1,#testDate2) AS DateDiff_Hours,
DATEDIFF(DAY,#testDate1,#testDate2) AS DateDiff_Days

Convert data and time into a numeric number in sql server

I have a data & time format column which I would like to convert to the following format in Microsoft SQL Server: yyyymmddhhmmss00000
So for example if I have 2021-02-04 11:49:50 this will be converted to 2021020411495000000.
Any one knows how to do it please?
You can use the FORMAT function:
SELECT FORMAT(myDate, 'yyyyMMddHHmmss00000')
By converting the date to NVARCHAR once with format 112 and once with format 8 you can extract the numeric date and the time without milliseconds. After removing : from the time you can concat these two strings and convert them to bigint. Following an example:
DECLARE #d DATETIME = GETDATE()
SELECT CAST(CONVERT(NVARCHAR(8), #d, 112) + REPLACE(CONVERT(NVARCHAR(8), #d, 8), ':', '') + '00000' AS BIGINT)

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

Converting separate columns for mm, dd, and yr into a workable mm/dd/year format

Basically I have 3 separate columns in a table. I will call them SMonth, Sday, Syear. They are stored as numeric values for some reason. I can use the following string to format them into what looks like a date but doesn't allow me to use functions such as sort, order by, datediff or dateadd.
CAST(SMonth AS varchar(2)) + '/' + CAST(SDay varchar(2)) + '/' + CAST(SYear AS varchar(4))
Anyone know how to convert this into a workable date, without changing the table?
It doesn't matter how it looks as long as I can use it ie a date or datetime makes no difference.
Thanks in advance.
Just convert your result into a date or datetime.
DECLARE #SMonth AS INT = 12
DECLARE #SDay AS INT = 31
DECLARE #SYear as INT = 2013
SELECT CONVERT(DATE,CAST(#SMonth AS varchar(2)) + '/' + CAST(#SDay AS varchar(2)) + '/' + CAST(#SYear AS varchar(4)))
you should convert format the string as yyyy/mm/dd in order to make sure that SQL Server uses ODBC canonical format
SELECT CONVERT(date, CONVERT(varchar, Syear) + '/' + convert(VARCHAR, SMonth) + '/' + convert(VARCHAR, SDay ) )
Otherwise it your results could depend on the default dateformat or someone changed it using SET DATEFORMAT, for example:
05/10/2013 could mean
May 10, 2013 if the DATEFORMAT is U.S.
October 5, 2013 if the DATEFORMAT is Brithish / French
see this for complete reference of dateformat

SQL - convert long integer to datetime

I have a database with dates in the following long integer format:
20100101000000
Where that would be Jan 1st, 2010, 00:00:00 for the time of day.
I want to be able to convert this to normal SQL Datetime syntax and back. Is this possible? I can only get this far:
SELECT CAST(CURRENT_TIMESTAMP as int);
Which returns '40556' - not exactly what Im after.
You could use substring to convert your string to yyyy-MM-dd HH:mm:ss notation, and cast that to a datetime:
select convert(datetime,
substring(sub.Dt,1,4) + '-' +
substring(sub.Dt,5,2) + '-' +
substring(sub.Dt,7,2) + ' ' +
substring(sub.Dt,9,2) + ':' +
substring(sub.Dt,11,2) + ':' +
substring(sub.Dt,13,2))
from (
select '20100101000000' as Dt
) sub
You can stuff it with the spaces and colons required:
select
stuff(stuff(stuff('20100101000000',9,0,' '),12,0,':'),15,0,':') STR,
convert(datetime,stuff(stuff(stuff('20100101000000',9,0,' '),12,0,':'),15,0,':')) DT;
The result is
STR | DT
20100101 00:00:00 | 2010-01-01 00:00:00.000
The first one shows the string it is converted to, the 2nd the datetime value.
To go in reverse
select
convert(char(8),getdate(),112) + replace(convert(varchar(30),getdate(),108),':','');
Replace the constants '20100101000000' and "getdate()" with field names where required if selecting from a table.