How to convert Datetime to String then String to Datetime - sql

This is the line.
DECLARE #Duration DATETIME = '2019-01-12'
DECLARE #DateFrom DATETIME = CONVERT(DATETIME, DATEADD(dd, -90, CONVERT(VARCHAR(10), #Duration)))
SELECT #DateFrom
This is the error message
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value.
and the sql results is NULL but 1 row affected.

Stop using CONVERT() to begin with, you don't need it!
DATEADD() can take in a DATETIME variable as-is and return a DATETIME:
DECLARE #Duration DATETIME = '2019-01-12'
DECLARE #DateFrom DATETIME = DATEADD(dd, -90, #Duration)
SELECT #DateFrom
It can also take in a date/time string literal and returns a DATETIME:
DECLARE #DateFrom DATETIME = DATEADD(dd, -90, '2019-01-12')
SELECT #DateFrom

Using DATEADD function, your query would be something like this depending on what you afforded in your problem :
DECLARE #Date datetime2 = '2011-09-23 15:48:39.2370000'
SELECT DATEADD(day,-90,#Date)

DECLARE #DateVariable DATETIME
SET #DateVariable = '2019-01-12'
DECLARE #DateFrom DATETIME = CONVERT(DATETIME, DATEADD(dd, -90, CONVERT(VARCHAR(10), #DateVariable,103)))
SELECT #DateFrom
I find an answer here. The problem is with the time zone setting. Specify in other formats like mm/dd/yyyy (usually works).
SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

Related

Date losing value when being stored

I'm trying to get a set of dates into a particular format (ddmmyy) so that they can be run against a number of scripts that I have.
I have managed to convert the date into the correct format, but when I try to store this as a variable it just returns as null or the un-formatted date.
DECLARE #CurrentDate SMALLDATETIME
SELECT #CurrentDate = getdate()
SELECT #CurrentDate = DATEADD(day, -1, #CurrentDate)
SELECT #CurrentDate = STR_REPLACE(CONVERT(varchar,#CurrentDate,3),'/',null)
--Returns this:
20-Mar-2002 00:00:00
DECLARE #CurrentDate SMALLDATETIME
SELECT #CurrentDate = getdate()
SELECT #CurrentDate = DATEADD(day, -1, #CurrentDate)
SELECT STR_REPLACE(CONVERT(varchar,#CurrentDate,3),'/',null)
--Returns this:
020320
I believe the problem comes from the fact that my declared variable is a smalldatetime object but I'm not sure of how to convert it correctly into a string that can be stored as a variable?
I've tried having a second variable and declaring it as a varchar and then storing my date as the varchar but this isn't working either:
DECLARE #CurrentDate SMALLDATETIME
DECLARE #CurrentDateFinal VARCHAR
SELECT #CurrentDate = getdate()
SELECT #CurrentDate = DATEADD(day, -1, #CurrentDate)
SELECT #CurrentDateFinal = CAST(STR_REPLACE(#CurrentDate,'/',null) AS VARCHAR)
--Returns this:
03-Mar-2020 00:00:00
You can do the current date amendment with the dateadd all in one line - there's no need to do two lines. The below gives you the DDMMYY output although I wouldn't use that format personally as you can come unstuck with regional differences (e.g. US prefer MMDDYY and UK tends to be DDMMYY). Also always use 4 digit years IMO.
DECLARE #FirstDate SMALLDATETIME
DECLARE #FinalDate varchar(20)
SELECT #FirstDate = DATEADD(day, -1,getdate())
set #FinalDate = STR_REPLACE(CONVERT(varchar,#FirstDate,3),'/',null)
SELECT #FinalDate
--------------------
030320
(1 row affected)

It is possible to combine date and time and stored into datetime format

Here what I am trying
CREATE TABLE #date (dt datetime)
declare #date Date ='2019-01-29',
#time time='11:06:31.095',
INSERT INTO #date
SELECT CONVERT(NVARCHAR,CONVERT(NVARCHAR,#date)+' '+CONVERT(NVARCHAR,#time))
It gives error:
Conversion failed when converting date and/or time from character
string.
SQL Server allows you to add datetime values, so you can do:
select convert(datetime, #date) + convert(datetime, #time)
You can try this
CREATE TABLE #date (dt datetime)
declare #date Date ='2019-01-29'
declare #time time='11:06:31.095'
INSERT INTO #date
SELECT CONVERT(datetime,#date)+ CONVERT(datetime,#time)
select * from #date

SQL Conversion error when converting date and/or time from character string

Query from yesterday date from 5pm
Declare #DATEFROM DATETIME=CONVERT(VARCHAR(10),GETDATE()-1,103) + '17:00:00.00'
select #DATEFROM
Expecting 2018-02-05 17:00:00
Conversion failed when converting date and/or time from character string.
SQL Server 2008. Need format yyyy-mm-dd (2018-02-05 17:22:00.000)
An easy implementation:
SELECT DATEADD(HOUR, 17, GETDATE()-1 - CAST(getDate() as time))
Instead of adding a date string, use dateadd:
Declare #DATEFROM DATETIME=dateadd(hh,17,CONVERT(VARCHAR(10),GETDATE()-1,103))
select #DATEFROM
Or if you must add a date string, cast it into a datetime first:
Declare #DATEFROM DATETIME=CONVERT(VARCHAR(10),GETDATE()-1,103) + cast('17:00:00.00' as datetime)
select #DATEFROM
You have to get varchar first and then cast back to datetime
Declare #DATEFROM varchar(22) = CONVERT(VARCHAR(10),GETDATE()-1,103) + ' 17:00:00.00'
select CAST(#DATEFROM AS datetime)
I'm not sure what you are trying to accomplish, however this will produce the date with the time index you are looking for, unless specifically you're looking for yesterday's date in which you can replace the first 0 with 1
declare #date datetime = dateadd(day, datediff(day, 0, sysdatetime()), 0) + .70833333333333333333
select #date
declare #dateFrom datetime=cast(dateAdd(dd, - 1,cast(getDate() as date) ) as datetime) +'17:00:00'

Convert datetime and varchar to single date

I have a following database columns and the values
MyDate datetime and My_Time varchar(5)
the values stored are
2006-09-05 00:00:00.000 and 16:47
Now I want to add this two columns and get a single datetime value 2006-09-05 16:47:00.000
How can I do this in SQL ?
UPDATE:
Some rows have NULL values for DocDate and DocTime.
So i am getting error like Conversion failed when converting date and/or time from character string
Simply...
DECLARE #date DATETIME
DECLARE #time VARCHAR(5)
SET #date = '2006-09-05 00:00:00.000'
SET #time = '16:47'
SELECT CAST(#date + #time AS DATETIME) -- 2006-09-05 16:47:00.000
Try this:
select dateadd(ss, datediff(ss, 0, #My_Time), #MyDate)
Key point is to understand that it's the same as...
select dateadd(ss, datediff(ss, 0, cast(#My_Time as time)), #MyDate)
...but the conversion is done explicitly.
EDIT
For default time and/or date, use ISNULL or COALESCE as appropriate.
Example:
SELECT
CAST(
isnull(#date, '2000-1-1') +
isnull(#time, '0:0')
AS DATETIME)
Try
CAST(MyDate AS DATETIME) + CAST(MyTime AS DATETIME) as CombinedDate

TSQL strip date from datetime

What is the best way to strip the date from a DATETIME so only time is left to do a comparison?
I know I can do the following:
CONVERT(DATETIME, CONVERT(VARCHAR(8), GETDATE(),8))
But this involves convert and characters. If I wanted to check whether a time (including minutes) was between two other times stored in DATETIME columns, is there an elegant way to do this without having to rely on converting to character strings?
If you're using SQL 2008
SELECT CAST(GETDATE() AS TIME)
Try the TimeOnly function from Essential SQL Server Date, Time, and DateTime Functions:
create function TimeOnly(#DateTime DateTime)
returns datetime
as
begin
return dateadd(day, -datediff(day, 0, #datetime), #datetime)
end
go
Or simply cast the DateTime as Time in SQL Server 2008:
declare #time as time
set #time = cast(dateTimeVal as time)
DECLARE
#Now DateTime,
#Today DateTime,
#Time DateTime
SET #Now = GetDate()
SET #Today = DateAdd(dd, DateDiff(dd, 0, #Now), 0)
SET #Time = DateAdd(ss, DateDiff(ss, #Today, #Now), 0)
SELECT #Time
Just another way to get date and time from datetime.
datetime in SQL Server implemented as float value where whole part floor(value) is day from 1900-01-01 and fractional part (value - floor(value)) is part of twenty-four hours elapsed from start of day
select
d as [datetime],
cast(cast(T.d as float) - floor(cast(T.d as float)) as datetime) as [time],
cast(floor(cast(T.d as float)) as datetime) as [date]
from
(values
(getdate()),
('1753-01-01 23:59:59.700'),
('1899-12-31 00:00:00.300'),
('1900-01-01 00:00:00.300')
) as T(d);