I have a column of bigint type containing date & time information (like 1353056515, 1353067040, 1360839600 etc.)
My requirement is to get time difference in HOURS format between column which I mentioned above and current datetime.
I tried to find the solution, but those were so confusing. I'm new to SQL Server.
Please help.
Please try this.
declare #mydate datetime
DECLARE #LocalTimeOffset BIGINT
,#AdjustedLocalDatetime BIGINT
SET #LocalTimeOffset = DATEDIFF(second,GETDATE(),GETUTCDATE())
SET #AdjustedLocalDatetime = 1416474000 - #LocalTimeOffset
SELECT DATEADD(second,#AdjustedLocalDatetime, CAST('1970-01-01 00:00:00' AS datetime))
-- It will give you date 2014-11-20 14:30:00.000
The data difference operation:
select DATEDIFF(hour,#mydate,GETDATE())
or
Create Function
create FUNCTION dbo.fn_ConvertToDateTime (#Datetime BIGINT)
RETURNS DATETIME
AS
BEGIN
DECLARE #mydate datetime
DECLARE #LocalTimeOffset BIGINT
,#AdjustedLocalDatetime BIGINT
SET #LocalTimeOffset = DATEDIFF(second,GETDATE(),GETUTCDATE())
SET #AdjustedLocalDatetime = #Datetime - #LocalTimeOffset
SELECT #mydate=DATEADD(second,#AdjustedLocalDatetime, CAST('1970-01-01 00:00:00' AS datetime))
return #mydate
END;
GO
select mydate= dbo.fn_ConvertToDateTime (1416474000)
select DATEDIFF(hour,#mydate,GETDATE())
Hope that helps.
The number looks like a UNIX timestamp, which is the number of seconds since 1/1/1970 00:00:00 UTC. You can get the UNIX timestamp from a datetime with a simple DATEDIFF:
declare #date datetime='2014-11-20T10:00:00'
declare #epoch datetime='19700101'
select DATEDIFF(s,#epoch,#date)
To get the number of hours between two timestamps you simply need to divide the difference by 3600 (the number of seconds in an hour). You don't need to convert the timestamps to dates before calculating the difference :
declare #dateTS int=DATEDIFF(s,#epoch,#date)
declare #nowTS int=DATEDIFF(s,#epoch,GETUTCDATE())
select (#nowTS-#dateTS)/3600.0
Note that I used 3600.0 to get a decimal result. If 3600 is used the fractional part will be truncated and you'll get 0 for differences less than 1 hour. This is OK if you want to return whole hours.
In a query you could write something like this:
select (DATEDIFF(s,#epoch,GETUTCDATE())-[MY_TS_COLUMN])/3600.0 AS Hours
from [MY_TABLE]
Related
I'm trying to convert a datetime from Asia/Manila to EST timezone
without declaring the exact interval like
date_sub(), subdate(), date_add(), adddate()
i find it easy to use
SELECT DATE_SUB('2016-04-04 13:00:00', INTERVAL 12 HOUR);
the result will be2016-04-04 01:00:00
But Im trying to create a dynamic script where i don't need to look how many hours is the difference between two timezone
and i find Convert_TZ() to do job
SELECT CONVERT_TZ('2016-04-04 13:00:00', 'Asia/Manila', 'EST');
but the result of this query is 2016-04-04 00:00:00
Maybe this native function is not including the "Daylight saving time(DST)"
Does anyone know how to do the trick?
where i can easily convert the time including the DST
to any timezone without hard coding the interval hour between the two timezone?
Thanks
Okay, my problem is solved, i use two option
First :
I simply use 'US/Eastern' not 'EST' to include the daylight in conversion.
Second:
Because I didn't know the first option earlier i do this to solve my problem at first.
I create a table that compose of the date where it is DST
which i found in some site online..
Then
I create a mysql function where its lookup to the table above
which if the specified date is between that DST Start and DST End it will automatically add 1 hour,
My function is like this,
CREATE FUNCTION usp_Convert(specified_date DATETIME, From_Timezone VARCHAR(20), To_Timezone VARCHAR(20), is_DST INT(1)) RETURNS datetime
DECLARE theDate DATETIME;
SET theDate = CONVERT_TZ(specified_date, From_Timezone, To_Timezone);
IF is_DST = 1 AND To_Timezone= 'EST' THEN
SET theDate = ADDDATE(theDate, INTERVAL 1 HOUR); END IF;
RETURN theDate;
This might not be the best answer but this totally solved my problem
Thanks.
This seems like overkill but is the only way I have been able to floor todays datetime to 00:00:00.000 at database level:
select CAST(FLOOR(CAST(CURRENT_TIMESTAMP AS float)) AS DATETIME)
I have tried using:
select FLOOR(getdate())
But get the following message:
Implicit conversion from data type datetime to float is not allowed. Use the CONVERT function to run this query.
Can anyone recommend another way of doing this?
Since you are using SQL Server 2008 you could make use of the date data type.
declare #Today date
set #Today = getdate()
select #Today
Or without the variable.
select cast(getdate() as date)
If you need to have the value as a datetime just cast it back to a datetime.
select cast(cast(getdate() as date) as datetime)
There are a lot of ways of doing this i have seen the floor one before. Here are a few more.
select cast(cast(CURRENT_TIMESTAMP as date) as datetime)
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 0)
SELECT CAST(CAST(CURRENT_TIMESTAMP - 0.50000004 AS int) AS datetime)
I normaly do the Cast to date version.
I need to convert character string to date format to fetch the first and last day of the month.
Input.
DECLARE #InpDat AS VARCHAR(20)
SET #InpDat = 201308
Expected output 2013-08-31
I need to get the first and last day of the given yearmonth. Can you please help me to get that.
I tried with the convert option but couldnt get it. ?
Use CAST(#InpDat + '01' AS DATE) to convert it to a date and DateAdd for the date arithmetic.
DECLARE #InpDat AS VARCHAR(20) SET #InpDat = '201308'
DECLARE #Month DATE SET #Month = CAST(#InpDat + '01' AS DATE)
SELECT #MONTH AS First,
DATEADD(day, -1, DATEADD(month, 1, #MONTH)) AS Last
DEMO
DECLARE #InpDat AS VARCHAR(20)
SET #InpDat = '201308'
SELECT CONVERT(DATETIME(#InpDat+'01') AS FirstDate,
DATEADD(dd,-1,DATEADD(mm,1,CONVERT(DATETIME(#InpDat+'01'))) AS LastDate
Why do you expect that a random number will convert to a date format without any cajoling? The database is a powerful tool but not magical.
You have to parse the number into a date, then format the date the way you like. I might suggest this sequence of calls:
-- assume you can separate the year and month into separate parts.
-- use 01 as default day for now, we'll get last day shortly.
DECLARE #IntermediateDate AS DATE SET #IntermediateDate = DATEFROMPARTS(2013,08,01)
-- Advance the month by one, and subtract one day to find the last day of the month.
SET #IntermediateDate = DATEADD( dd, -1, DATEADD( mm, 1, #IntermediateDate))
Now format using your favorite formatting functions.
I have two columns of Data type time. I'm using datediff to find the difference in hours.
The problem is when I try to find the difference between 00:00:00 to 06:00:00, it returns -18.
How can I fix it?
note: I need to calculate more difference with this so I can't just divide it with -3
my function- (datediff(HOUR, startHour, endHour))*60
Thanks in advance
You are not comparing 00:00:00 to 06:00:00. You have some date component
This gives -18 as an example
DECLARE #starthour datetime = '00:00:00';
DECLARE #endhour datetime = '18991231 06:00:00';
SELECT #starthour, #endhour, DATEDIFF(hour, #starthour, #endhour);
SET #starthour = '20120507 00:00:00';
SET #endhour = '20120506 06:00:00';
SELECT #starthour, #endhour, DATEDIFF(hour, #starthour, #endhour);
Reverse the parameters:
my function- (datediff(HOUR, endHour, startHour))*60
Edit:
The function DATEDIFF works with dates and for some reason, it thinks you're subtracting 6AM - Midnight (next day), which is 18 hours.
The following code sample works fine for me in SQL 2008, so you need to check your data type to make sure you're using TIME and not DATETIME or SMALLDATETIME.
declare #t1 time
set #t1 = '00:00:00'
declare #t2 time
set #t2 = '06:00:00'
select datediff(hour, #t1, #t2)
-- returns 6
Syntax:
DATEDIFF (datepart, startdate, enddate )
Examples:
SELECT DATEDIFF(hour, '00:00:00', '06:00:00');
Result: 6
SELECT DATEDIFF(hour, '00:00:00', '06:00:00')*60;
Result: 360
Refer DATEDIFF (Transact-SQL)
I'm late to the game, but I faced a similar problem.
DATEDIFF(HOUR,'23:00:00','06:00:00')
Result: -17
Reversing the two times (as suggested by another answer above) does not represent the time frame I want to capture. I don't want to know how many hours are between 6am and 11pm. I want 11pm to 6am.
To resolve this, wrap the DATEDIFF() in a CASE statement and add 24 when the start time is greater than the end time:
DECLARE #startTime TIME(0) = '23:00:00';
DECLARE #endTime TIME(0) = '06:00:00';
SELECT CASE WHEN #startTime > #endTime THEN 24 + DATEDIFF(HOUR,#startTime,#endTime) ELSE DATEDIFF(HOUR,#startTime,#endTime) END
Result: 7
I need to search between dates and times.
For example, between date: 30/02/2007, time: 10:32 and date: 21/06/2008, time: 14:19
What is the most simple query for this?
Thanks in advance.
you should look at the date time formats available in SQL Server: http://msdn.microsoft.com/en-us/library/ms187928.aspx
yyyy-mm-dd hh:mi is what you should use:
try:
SELECT
*
FROM Records
WHERE DateCreated>='2007-02-30 10:32' AND DateCreated<='2008-06-21 14:19'
in the above query the strings will be converted to datetime data type if DateCreated is a datetime column. and the query will work.
you can create local variables of datetime data type and use a query like:
DECLARE #StartDate datetime, #EndDate datetime
SELECT #StartDate='2007-02-30 10:32', #EndDate='2008-06-21 14:19'
SELECT
*
FROM Records
WHERE DateCreated>=#StartDate AND DateCreated<=#EndDate
I like using <, <=, >=, or > because it allows more flexibility than BETWEEN and forces you to think about including endpoints or not.
Another thing to consider is getting all data from a complete day:
DECLARE #StartDate datetime, #EndDate datetime
--set the days you want
SELECT #StartDate='2007-02-30 10:32', #EndDate='2008-06-21 14:19'
--remove the time
SELECT #StartDate=DATEADD(day,DATEDIFF(day,0,#StartDate),0), #EndDate=DATEADD(day,DATEDIFF(day,0,#EndDate),0)
--get everything on '2007-02-30' up to the end of the day on '2008-06-21'
SELECT
*
FROM Records
WHERE DateCreated>=#StartDate AND DateCreated<#EndDate+1
Try this:
SELECT
*
FROM
Records
WHERE
DateCreated BETWEEN #Date1 AND #Date2