SQL add Datetime add hour add Minute - sql

In my table I have DateTime, Hour column.
example : 2012-05-14 00:00:00.000 and 1230
How can I add this hour column into my Datetime column, so I can have
2012-05-14 12:30:00.000
I tried with this:
SELECT DATE_DEBUT, HEURE_DEBUT,
DATEADD(hour, CONVERT(int, SUBSTRING(HEURE_DEBUT, 0, 2)), DATE_DEBUT) AS DateTemp,
DATEADD(hour, CONVERT(int, SUBSTRING(HEURE_DEBUT, 2, 2)), DateTemp) AS DateComplete
FROM ESPTEMPS_PROGRAMMATION
but it does not work.
thanks you in advance,
Stev

From what I understand, you want to add the first two digits as hour, the second two as minute - but you're not doing this in your DATEADD calls - you're adding both parts as HOUR - try this instead:
SELECT DATE_DEBUT, HEURE_DEBUT,
DATEADD(MINUTE, CONVERT(int, SUBSTRING(HEURE_DEBUT, 3, 2)),
DATEADD(HOUR, CONVERT(int, SUBSTRING(HEURE_DEBUT, 1, 2)), DATE_DEBUT))
FROM ESPTEMPS_PROGRAMMATION
Here I'm using two nested DATEADD - the inner DATEADD adds the hours, the outer adds the minutes onto the result of adding the hours.
Also: SUBSTRING in SQL Server is 1-based, e.g. the first character of a string is at position 1 (not 0, as you seem to assume)

Related

Is there a way to add fractions in dateadd

I was surprised to see this query gives two columns with identical values
select
dateadd(hour, -1.5, GETUTCDATE()) as OneAndAHalf,
dateadd(hour, -1, GETUTCDATE()) as One
Is it possible to use dateadd in this way, or am I going to have to calculate the datetime in code?
According to the Docs the answer is no. You cannot add a non-integer value (either as a literal or as an expression) as 'number' in the DATEADD function.
As other members mentioned: switch the DATEPART to an appropriate interval (like minutes) and use that instead. To add "fractions of a second" you could use 'millisecond' which adds thousandth's of a second.
select getdate()
union all
select dateadd(millisecond,100, getdate())
(No column name)
2021-08-06 11:15:04.260
2021-08-06 11:15:04.360
Syntax SQL
DATEADD (datepart , number , date )
number An expression that can resolve to an int that DATEADD adds to a
datepart of date. DATEADD accepts user-defined variable values for
number. DATEADD will truncate a specified number value that has a
decimal fraction. It will not round the number value in this
situation.
Multiply your increment by 60 and add it as minutes (or multiply them by 3600 and add it as seconds)
select
dateadd(minute, -1.5 * 60, GETUTCDATE()) as OneAndAHalf,
dateadd(minute, -1 * 60, GETUTCDATE()) as One
select
dateadd(second, -1.5 * 3600, GETUTCDATE()) as OneAndAHalf,
dateadd(second, -1 * 3600, GETUTCDATE()) as One

SQL Date only in Where clause [duplicate]

If I have a date value like 2010-03-01 17:34:12.018
What is the most efficient way to turn this into 2010-03-01 00:00:00.000?
As a secondary question, what is the best way to emulate Oracle's TRUNC function, which will allow you to truncate at Year, Quarter, Month, Week, Day, Hour, Minute, and Second boundaries?
To round to the nearest whole day, there are three approaches in wide use. The first one uses datediff to find the number of days since the 0 datetime. The 0 datetime corresponds to the 1st of January, 1900. By adding the day difference to the start date, you've rounded to a whole day;
select dateadd(d, 0, datediff(d, 0, getdate()))
The second method is text based: it truncates the text description with varchar(10), leaving only the date part:
select convert(varchar(10),getdate(),111)
The third method uses the fact that a datetime is really a floating point representing the number of days since 1900. So by rounding it to a whole number, for example using floor, you get the start of the day:
select cast(floor(cast(getdate() as float)) as datetime)
To answer your second question, the start of the week is trickier. One way is to subtract the day-of-the-week:
select dateadd(dd, 1 - datepart(dw, getdate()), getdate())
This returns a time part too, so you'd have to combine it with one of the time-stripping methods to get to the first date. For example, with #start_of_day as a variable for readability:
declare #start_of_day datetime
set #start_of_day = cast(floor(cast(getdate() as float)) as datetime)
select dateadd(dd, 1 - datepart(dw, #start_of_day), #start_of_day)
The start of the year, month, hour and minute still work with the "difference since 1900" approach:
select dateadd(yy, datediff(yy, 0, getdate()), 0)
select dateadd(m, datediff(m, 0, getdate()), 0)
select dateadd(hh, datediff(hh, 0, getdate()), 0)
select dateadd(mi, datediff(mi, 0, getdate()), 0)
Rounding by second requires a different approach, since the number of seconds since 0 gives an overflow. One way around that is using the start of the day, instead of 1900, as a reference date:
declare #start_of_day datetime
set #start_of_day = cast(floor(cast(getdate() as float)) as datetime)
select dateadd(s, datediff(s, #start_of_day, getdate()), #start_of_day)
To round by 5 minutes, adjust the minute rounding method. Take the quotient of the minute difference, for example using /5*5:
select dateadd(mi, datediff(mi,0,getdate())/5*5, 0)
This works for quarters and half hours as well.
If you are using SQL Server 2008+, you can use the Date datatype like this:
select cast(getdate() as date)
If you still need your value to be a DateTime datatype, you can do this:
select cast(cast(getdate() as date) as datetime)
A method that should work on all versions of SQL Server is:
select cast(floor(cast(getdate() as float)) as datetime)
Try:
SELECT DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)
UPDATE: answer on the second question:
for years you could use a little bit modified version of my answer:
SELECT DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)
for quarter:
SELECT DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), 0)
and so on.
I checked, up to minutes - it's OK. But on seconds I've got an overflow message:
Difference of two datetime columns
caused overflow at runtime.
One more update: take a look to the following answer to the same question
This is late, but will produce the exact results requested in the post. I also feel it is much more intuitive than using dateadd, but that is my preference.
declare #SomeDate datetime = '2010-03-01 17:34:12.018'
SELECT
DATEFROMPARTS(
YEAR(#SomeDate)
,MONTH(#SomeDate)
,'01'
) AS CUR_DATE_FROM_PARTS
,DATETIMEFROMPARTS(
YEAR(#SomeDate)
,MONTH(#SomeDate)
,'01' --DAY(#SomeDate)
,'00' --DATEPART(HOUR,#SomeDate)
,'00' --DATEPART(MINUTE,#SomeDate)
,'00' --DATEPART(SECOND,#SomeDate)
,'00' --DATEPART(MILLISECOND,#SomeDate)
) AS CUR_DATETIME_FROM_PARTS
,#SomeDate AS CUR_DATETIME
,YEAR(#SomeDate) AS CUR_YEAR
,MONTH(#SomeDate) AS CUR_MONTH
,DAY(#SomeDate) AS CUR_DAY
,DATEPART(HOUR,#SomeDate) AS CUR_HOUR
,DATEPART(MINUTE,#SomeDate) AS CUR_MINUTE
,DATEPART(SECOND,#SomeDate) AS CUR_SECOND
,DATEPART(MILLISECOND,#SomeDate) AS CUR_MILLISECOND
FROM Your_Table
Truncated Date: 2010-03-01
Truncated DateTime: 2010-03-01 00:00:00.000
DateTime: 2010-03-01 17:34:12.017
Not sure if this is the most efficient, but I like the simplicity in using the following where #SomeDate is your field.
Concat(Year(#SomeDate), '-', Month(#SomeDate), '-', '01')
If you want to truncate a date to the start of the week in a way that is independent of SET DATEFIRST you can:
--change a date backwards to nearest Monday
DATEADD(DAY, (DATEPART(dw, '2001-01-01') - DATEPART(dw, YOUR_COLUMN)-7)%7, YOUR_COLUMN)
Breaking this down:
DATEPART(dw, '2001-01-01') - DATEPART(dw, YOUR_COLUMN): the dw of a known Monday (2001-01-01 was a Monday) minus the dw of your date, effectively giving the "number of days difference between your date and Monday" or "how many days back do we have to scroll your date to make it into Monday"
( ... -7)%7 - we subtract 7 from it and modulo the result by 7.
We do this because if e.g. DATEFIRST is 7 (Sunday), and your date column is Sunday then your dw is 1, and your known Monday is 2.
This means the result of the dw_for_known_monday - dw_for_your_date is +1 rather than -6
This would then mean that DATEADD will roll your date forwards to the following Monday rather than backwards to the previous Monday
If we subtract 7 off it then the result would definitely be negative, but then we wouldn't want your Mondays (which are 0 days different from the known Monday) to end up doing a DATEADD of -7, so we modulo the result by 7.
This turns any problematic -7 into 0, which means your DATEADD will only ever have a "number of days" argument between -6 and 0
DATEADD(DAY, (DATEPART(dw, '2001-01-01') - DATEPART(dw, YOUR_COLUMN)-7)%7, YOUR_COLUMN) - we then DATEADD the (negative) number of days from the above step
If you want to roll your date backwards to e.g. a Sunday, change the date 2001-01-01 to a date that is a known Sunday (like 2000-12-31), etc

TSQl: Select Current Date - 6 Days and set time to 12:01 AM

I am trying to get current date - 6 days. That is easy.
Now I am trying to get current date - 6 days + 12:01 AM.
So if today is 3-2-2012 11:14 AM.
I want to get 2-25-2012 12:01 AM
These 2 selects will give me current date - 6, but will not reset the time to 12:01 AM
select getdate()-6
SELECT DATEADD(day, -6, CURRENT_TIMESTAMP);
SELECT DATEADD(minute, 1, DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) - 6, 0))
is equivalent to
SELECT DATEADD(minute, 1, DATEADD(DAY, DATEDIFF(DAY, '19000101', GETDATE()) - 6, '19000101'))
I think you will find this option faster and more flexible than the varchar implementations. by keeping the data types as they are, you don't have to worry about the vagaries of the cast/convert results.
See Louis Davidson for one of the full explainations:
http://sqlblog.com/blogs/louis_davidson/archive/2011/02/09/some-date-math-fun.aspx
Using the following will give you the result in a datetime format:
SELECT CAST(Convert(varchar(10), DateAdd(d, -6, getdate()), 101)
+ ' 12:01 AM' as datetime)
Result: 2012-02-25 00:01:00.000
Once you have the datetime that you want, you can convert it to many different formats.
Or you can do the following which is in a varchar format:
select Convert(varchar(10), DateAdd(d, -6, getdate()), 110) + ' 12:01 AM'
which results in 02-25-2012 12:01 AM
One less conversion that #Phil Helmer's solution:
SELECT DATEADD(DAY, DATEDIFF(DAY, '19000101', GETDATE()), '1899-12-26T12:01:00')
Since some people are apparently unaware that everything "to the right" of the element specified in that DATEADD/DATEDIFF pair is effectively taken from the right-hand constant. Everything "to the left" (and including the actual element) can be used to achieve offsetting effects.
(The above left/right are assuming that the entire datetime value is being interpreted with year to the left and milliseconds to the right, with all intermediate values in "size" order)
Edited - I've also updated my answer to subsume the -6 into the right-hand value. Its possible to create all kinds of offsetting by picking suitable values for the two constants.
The relationship between the two datetime constants specified in the expression ought to be expressed, at least in a comment alongside the usage. In the above, I'm using 1/1/1900 as a base point, and computing the number of midnight transitions between then and now (as DATEDIFF always works). I'm then adding that number of days onto the point in time 6 days earlier (e.g. 26/12/1899) at exactly 00:01 in the morning...
SELECT DATEADD(dd, -6, DATEDIFF(dd, 0, GETDATE())) + '12:01'

Sybase- sql query where date in last x days without considering time part

I need to write a sybase query that will have a where clause with date within last x days like so -
SELECT *
FROM table_name
WHERE
date_col > [_last_x_days]
I was able to get datetime of last x days using
dateadd(day, -x, getdate())
However, the above method still gives me the time element based on when the query is run. How can I strip down the time part?
i.e. convert 10-10-2011 15:00:45 to 10-10-2011 00:00:00
Also, is there a better way to do this?
Thanks in advance!!!
J
The convert function will return the date without the time component.
dateadd( day, -x, CONVERT(DATE, getdate(), 103) )
See this link for a complete description of CONVERT.
How about this?
convert(datetime, substring(convert(varchar, dateadd(day, -x, getdate()), 20), 1, 11))

Simplest way to create a date that is the first day of the month, given another date

In SQL Server what is the simplest/cleanest way to make a datetime representing the first of the month based on another datetime? eg I have a variable or column with 3-Mar-2005 14:23 and I want to get 1-Mar-2005 00:00 (as a datetime, not as varchar)
Select DateAdd(Month, DateDiff(Month, 0, GetDate()), 0)
To run this on a column, replace GetDate() with your column name.
The trick to this code is with DateDiff. DateDiff returns an integer. The second parameter (the 0) represents the 0 date in SQL Server, which is Jan 1, 1900. So, the datediff calculates the integer number of months since Jan 1, 1900, then adds that number of months to Jan 1, 1900. The net effect is removing the day (and time) portion of a datetime value.
SELECT DATEADD(mm, DATEDIFF(mm, 0, #date), 0)
Something like this would work....
UPDATE YOUR_TABLE
SET NewColumn = DATEADD(day, (DATEPART(day, OldColumn) -1)*-1, OldColumn)
Just use
DATEADD(DAY, 1-DAY(#date), #date)