SQL Server convert number to date - sql-server

How do I convert a numbers in the columns with values like 20160912 into date formats of the form 09/12/2016 and order them by the dates in the date format.

You can use cast and convert built-in functions. Depending on what type is 20160912 you can do following.
A) int
declare #d int=20160912
select convert(varchar(20),convert(date,convert(varchar,#d)),101)
--step by step
declare #dStr varchar(20)
set #dStr = convert(varchar,#d) --'20160912'
-- or = cast(#d as varchar)
declare #dDate date --or datetime
set #dDate = convert(date, #dStr) --2016-09-12 (this is external representation)
--show in MM/dd/yyyy format
select convert(varchar(20), #dDate, 101) --magic 101 for MM/dd/yyyy
--09/12/2016
B) varchar just omit innermost conversion

Related

Convert varchar datetime without dashes and colon to varchar datetime with dashes and colon

I want to convert this 20201001163318 varchar date & time to something like this 2020-10-01 16:33:18.
I tried this
select convert(varchar, getdate(), 25)
but it does not work
Perhaps stuff() in concert with a try_convert()
Example
declare #S varchar(50) = '20201001163318'
Select try_convert(varchar(19),try_convert(datetime,stuff(stuff(stuff(#S,13,0,':'),11,0,':'),9,0,' ')),120)
Returns
(No column name)
2020-10-01 16:33:18
Also if you wanted to convert getdate() to a string, you could try:
Select convert(varchar(19),getdate(),120)

SQL convert date dmmyyyy and ddmmyy to yyyy-mm-dd

I have the following problem.
I have some dates with the following format '15122019' and I need it in this format 2019-12-15, which I already solved it in the following way.
select convert (date, Stuff(Stuff('15122018',5,0,'.'),3,0,'.'),104)
The real problem is when the dates come like this '3122019' the conversion can not be done because the length is shorter. Is ther e another way to do it? I've been trying to solve it for several hours. And another question, can this query be parameterized?
Try this:
DECLARE #date VARCHAR(20)
SET #date ='3122019'
IF(LEN(#date) = 8)
BEGIN
SET #date = Stuff(Stuff(#date,5,0,'.'),3,0,'.');
SELECT CONVERT(DATE, #date , 103);
END
ELSE IF(LEN(#date) = 7)
BEGIN
SET #date = Stuff(Stuff(#date,4,0,'.'),2,0,'.');
IF(ISDATE(#date)=1)
BEGIN
SELECT CONVERT(DATE, #date , 103);
END
ELSE
BEGIN
SET #date = Stuff(Stuff(#date,4,0,'.'),3,0,'.');
SELECT CONVERT(DATE, #date , 103);
END
END
ELSE IF(LEN(#date) = 6)
BEGIN
SET #date = Stuff(Stuff(#date,3,0,'.'),2,0,'.');
SELECT CONVERT(DATE, #date , 103);
END
You can add 0 to the left and take 8 chars with right. like RIGHT('0'+'15122018',8). it work with 15122018 and 3122018
select convert (date, Stuff(Stuff( RIGHT('0'+'15122018',8) ,5,0,'.'),3,0,'.'),104)
Such conversation can be achieved by:
Casting integer value to DATE using intermediate FORMAT transformation to a recognizable for conversation string pattern.
style 105 applied to match the input as dd-mm-yyyy
style 05 to match dd-mm-yy
SQL:
-- input format: dmmyyyy
SELECT CONVERT(DATE, FORMAT(3012019, '##-##-####'), 105)
-- result: 2019-01-03
-- input format: dmmyy
SELECT CONVERT(DATE, FORMAT(30119, '##-##-##'), 05)
-- result: 2019-01-03
This will work fine with a single (and double) digit day number, however, it indeed requires a double-digit month

How to change date-time format?

I have a RegDate column of nvarchar(max) type in my table in which dates are stored in mm/dd/yyyy (5/22/2015 11:09:39 PM) and dd-mm-yyyy (19-05-2015 22:55:05) format. I want to get all these entries in one format i.e. dd/mm/yyyy. I tried to convert it by using
Convert(varchar(10),cast(vr.RegDate as DATETIME),105) as RegistrationDate
but it gives following error:
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
Please help me regarding this problem.
You need to determine the format of the value you are converting before you can convert it. If it's simply between those two formats, you can simply search for - to determine it's format.
I would also suggest storing the value in a datetime column as opposed to a varchar, and if you can't do that for whatever reason, you should definitely store it in an ISO format: YYYY-MM-DD HH:MM:SS.
Here's a sample that uses a case statement to provide optional formatting of your two date formats, using the presence of the - character:
CREATE TABLE #temp ( RegDate VARCHAR(50) )
INSERT INTO #temp
( RegDate )
VALUES ( '5/22/2015 11:09:39 PM' ),
( '19-05-2015 22:55:05' )
SELECT CASE WHEN CHARINDEX('-', RegDate) != 0
THEN CONVERT(DATETIME, RegDate, 105)
ELSE CONVERT(DATETIME, RegDate, 101)
END AS FormattedToDate
FROM #temp
DROP TABLE #temp
Produces:
FormattedToDate
2015-05-22 23:09:39.000
2015-05-19 22:55:05.000

How to solve the date comparison issue in SQL Server?

I am using the following way to compare two dates:
if CONVERT(varchar(20), #ScheduleDate, 101) >= CONVERT(varchar(20), #CurrentDateTime, 101)
This is working fine for the current year, but when the comes in yearly like one date is 12/31/2012 and 1/1/2013 then its not working.
Please help me how can I resolve this.
why do you comparing strings?
you can compare dates
if #ScheduleDate >= #CurrentDateTime
but if your date contains time, I usually do
if convert(nvarchar(8), #ScheduleDate, 112) >= convert(nvarchar(8), #CurrentDateTime, 112)
112 datetime format is YYYYMMDD so it's good for compare dates
You have to remember that string comparison is from left to right, so "1/...." is smaller than "12/...".
You need to use DATETIME comparisons, not string comparison.
Something like
DECLARE #ScheduleDate DATETIME = '1/1/2013',
#CurrentDateTime DATETIME = '12/31/2012'
IF (#ScheduleDate >= #CurrentDateTime)
BEGIN
SELECT #ScheduleDate, #CurrentDateTime
END
DECLARE #ScheduleDateString VARCHAR(20) = '1/1/2013',
#CurrentDateTimeString VARCHAR(20) = '12/31/2012'
IF (CONVERT(DATETIME,#ScheduleDateString,101)>=CONVERT(DATETIME,#CurrentDateTimeString,101))
BEGIN
SELECT CONVERT(DATETIME,#ScheduleDateString,101),CONVERT(DATETIME,#CurrentDateTimeString,101)
END
SQL Fiddle DEMO
Note that if the variables are already datetimes, you do not need to convert them.
Assuming that both variables are currently DateTime variables, can't you just compare them without converting to strings?
declare #ScheduleDate DATETIME, #CurrentDateTime DATETIME
SET #ScheduleDate = '1 Jan 2013'
SET #CurrentDateTime = GetDate()
IF (#ScheduleDate >= #CurrentDateTime)
BEGIN
SELECT 'Do Something'
END
ELSE
BEGIN
SELECT 'Do Something Else'
END
when you use CONVERT(nvarchar(8), #ScheduleDate, 112) function it's return string instead of date.
so,
Use "112" DateFormat in Sql Server it's return string in "YMD" format without any sepration.
compare that string in your query and get desire output.
Such as "if CONVERT(nvarchar(8), #ScheduleDate, 112) >= CONVERT(nvarchar(8), #CurrentDateTime, 112)"
I would not use CONVERT to compare formatted strings. It is slow (well, more like microseconds, but still)
I use a UDF for SQL prior to version 2008
CREATE FUNCTION [dbo].[DateOnly] (#Date DateTime)
RETURNS Datetime AS
BEGIN
Return cast (floor (cast (#Date as float)) as DateTime)
END
and for versions >=2008 this approach
select convert(#MyDateTime as DATE)
Of course, you can compare datetime values directly, but to know whether two datetime values are on the same date (ignoring the time component), the above versions have proven to be effectivy.
Date : From and To with following format
from_Date# = #dateformat("#form.from#", "mm/dd/yyyy")
to_Date# = #dateformat("#now()#" + 1, "mm/dd/yyyy")
In SQL Statement
WHERE a.DateCreated >= CAST ('#from_date#' AS DATE) and a.DateCreated <= CAST('#to_date#' AS DATE)
This is working fine without any cast of original date time column

SQL Server adding one month to a date represented as an 8 digit decimal

A SQL Server application we use (accpac) represents dates as an 8 digit decimal in ISO format (example: today's date is 20100802)
I need to add one month to this. I've found a way to do it, but there must be a better way.
The steps of my solution are:
declare #accpacDate as decimal
set #accpacDate = 20100101
declare #date1 as date
declare #date2 as date
set #date1=cast(CAST(#accpacDate as varchar(8)) as datetime) /*get the starting value as a date */
set #date2=DATEADD(month,1,#date1)
select CONVERT(varchar(8),#date2,112) as aVarchar
select convert(decimal,CONVERT(varchar(8),#date2,112)) as aDecimal
SELECT CONVERT(VARCHAR(8),DATEADD(MONTH,1,CONVERT(VARCHAR(8),20100802,112)),112)
It seems about right what you are doing.
String and Date manipulation is pretty core in SQL, no fancy wrappers for auto-converting and manipulating date formats (accpac, memories, shiver).
You could write that into a user function, to add days to a accpac date, and return the result:
create function accpacadd
( #accpacdate decimal,
#days int)
RETURNS decimal
AS BEGIN
declare #date1 as datetime
set #date1=cast(CAST(#accpacDate as varchar(8)) as datetime) /*get the starting value as a date */
set #date1=DATEADD(day, #days, #date1)
return convert(decimal, CONVERT(varchar(8), #date1, 112))
END
So then you can just call it with min code:
select dbo.accpacadd(20100102, 5)
select dbo.accpacadd(20100102, -5)
Gives 20100107 and 20091228 respectively

Resources