Can I query a DateTime in a SQL Server view using timezone? - sql

I have a DateTime field in SQL Server 2008 R2. I have some views that query that field such as
SELECT *
FROM table1
WHERE CONVERT(DATE, TransactionDate) = 'April 10 2012'.
The servertime is set to texas time, and I want to query this data using EST. In other words
SELECT *
FROM Table1
WHERE TransactionDate = 'April 10 2012 Eastern Standard Time'
What is the best way to achieve this?

Give this a shot.
"DATETIMEOFFSET Datatype
Currently when saving the date and time in a column, it will not indicate what time zone that date and time belongs to. This can be especially important when you are dealing with data including several different countries with different time zones. The new datatype DATETIMEOFFSET defines a date that is combined with a time of a day that has time zone awareness and is based on a 24-hour clock. The following script illustrates the usage of the DATETIMEOFFSET datatype.
DECLARE #dt DATETIMEOFFSET(0)
SET #dt = '2007-10-29 22:50:55 -1:00'
DECLARE #dt1 DATETIMEOFFSET(0)
SET #dt1 = '2007-10-29 22:50:55 +5:00'
SELECT DATEDIFF(hh,#dt,#Dt1)
http://www.sql-server-performance.com/2007/datetime-2008/

Related

SQL Server to SYnapse SQL syntax modifications

I have a query that works just fine in SQL Server but I would like some help with the required syntax modifications to make it work at Synapse SQL. Any help would be appreciated! The id's are unix timestamps. I want to count the id's of the previous day filtering by time range using the unix timestamps
SELECT COUNT(Id)
FROM [dbo].[name]
WHERE Id >= CONVERT(bigint, DATEDIFF(SECOND,'1970-01-01', CONVERT(date,dateadd(d, -1, GETDATE()))))*1000
and Id < CONVERT(bigint, DATEDIFF(SECOND,'1970-01-01', CONVERT(date,GETDATE())))*1000
When SQL servers and Azure Synapse are in different time zones, the results of Query will be varying. Azure Synapse will be in UTC time zone.
In order to convert current date value to local datetime value in azure synapse, User defined function is created as in below script.
Create FUNCTION [dbo].[CurrentLocalTime]( #TimeZoneName sysname )
RETURNS datetime
AS
BEGIN
RETURN DATEADD(hour,
TRY_CAST((SELECT REPLACE(current_utc_offset, N':', N'.')
FROM sys.time_zone_info
WHERE [name] = #TimeZoneName) AS decimal(18,2)),
SYSDATETIME());
END;
Instead of using getdate() of function, the above function is used in the query.
Query
SELECT COUNT(Id) FROM sample1
WHERE Id >= CONVERT(bigint, DATEDIFF(SECOND,'1970-01-01', CONVERT(date,dateadd(d, -1, dbo.CurrentLocalTime('AUS Eastern Standard Time' )))))*1000
and Id < CONVERT(bigint, DATEDIFF(SECOND,'1970-01-01', CONVERT(date,dbo.CurrentLocalTime('AUS Eastern Standard Time' ))))*1000
The time zone can be replaced in the query as per the requirement.
Results for Sample data:

SQLServer remove Date part of datetime [duplicate]

How would I be able to extract the time part of a DateTime field in SQL? For my project I have to return data that has a timestamp of 5pm of a DateTime field no matter what the date is
This will return the time-Only
For SQL Server:
SELECT convert(varchar(8), getdate(), 108)
Explanation:
getDate() is giving current date and time.
108 is formatting/giving us the required portion i.e time in this case.
varchar(8) gives us the number of characters from that portion.
Like:
If you wrote varchar(7) there, it will give you 00:00:0
If you wrote varchar(6) there, it will give you 00:00:
If you wrote varchar(15) there, it will still give you 00:00:00 because it is giving output of just time portion.
SQLFiddle Demo
For MySQL:
SELECT DATE_FORMAT(NOW(), '%H:%i:%s')
SQLFiddle Demo
In SQL Server if you need only the hh:mi, you can use:
DECLARE #datetime datetime
SELECT #datetime = GETDATE()
SELECT RIGHT('0'+CAST(DATEPART(hour, #datetime) as varchar(2)),2) + ':' +
RIGHT('0'+CAST(DATEPART(minute, #datetime)as varchar(2)),2)
If you want only the hour of your datetime, then you can use DATEPART() - SQL Server:
declare #dt datetime
set #dt = '2012-09-10 08:25:53'
select datepart(hour, #dt) -- returns 8
In SQL Server 2008+ you can CAST() as time:
declare #dt datetime
set #dt = '2012-09-10 08:25:53'
select CAST(#dt as time) -- returns 08:25:53
I know this is an old question, but since the other answers all
return strings (rather than datetimes),
rely on the internal representation of dates (conversion to float, int, and back) or
require SQL Server 2008 or beyond,
I thought I'd add a "pure" option which only requires datetime operations and works with SQL Server 2005+:
SELECT DATEADD(dd, -DATEDIFF(dd, 0, mydatetime), mydatetime)
This calculates the difference (in whole days) between date zero (1900-01-01) and the given date and then subtracts that number of days from the given date, thereby setting its date component to zero.
Try this in SQL Server 2008:
select *
from some_table t
where convert(time,t.some_datetime_column) = '5pm'
If you want take a random datetime value and adjust it so the time component is 5pm, then in SQL Server 2008 there are a number of ways. First you need start-of-day (e.g., 2011-09-30 00:00:00.000).
One technique that works for all versions of Microsoft SQL Server as well as all versions of Sybase is to use convert/3 to convert the datetime value to a varchar that lacks a time component and then back into a datetime value:
select convert(datetime,convert(varchar,current_timestamp,112),112)
The above gives you start-of-day for the current day.
In SQL Server 2008, though, you can say something like this:
select start_of_day = t.some_datetime_column
- convert(time, t.some_datetime_column ) ,
from some_table t
which is likely faster.
Once you have start-of-day, getting to 5pm is easy. Just add 17 hours to your start-of-day value:
select five_pm = dateadd(hour,17, t.some_datetime_column
- convert(time,t.some_datetime_column)
)
from some_table t
Note that from MS SQL 2012 onwards you can use FORMAT(value,'format')
e.g. WHERE FORMAT(YourDatetime,'HH:mm') = '17:00'
"For my project, I have to return data that has a timestamp of 5pm of a DateTime field, No matter what the date is."
So I think what you meant was that you needed the date, not the time. You can do something like this to get a date with 5:00 as the time:
SELECT CONVERT(VARCHAR(10), GetDate(), 110) + ' 05:00:00'
This should strip away the date part:
select convert(datetime,convert(float, getdate()) - convert(int,getdate())), getdate()
and return a datetime with a default date of 1900-01-01.
you can use CONVERT(TIME,GETDATE()) in this case:
INSERT INTO infoTbl
(itDate, itTime)
VALUES (GETDATE(),CONVERT(TIME,GETDATE()))
or if you want print it or return that time use like this:
DECLARE #dt TIME
SET #dt = CONVERT(TIME,GETDATE())
PRINT #dt
select cast(getdate() as time(0))
returns for example :- 15:19:43
replace getdate() with the date time you want to extract just time from!
SELECT DISTINCT
CONVERT(VARCHAR(17), A.SOURCE_DEPARTURE_TIME, 108)
FROM
CONSOLIDATED_LIST AS A
WHERE
CONVERT(VARCHAR(17), A.SOURCE_DEPARTURE_TIME, 108) BETWEEN '15:00:00' AND '15:45:00'
declare #datetime as datetime
set #datetime = getdate()
select cast(cast(#datetime as time) as varchar(8))
For year:
SELECT DATEPART(YEAR, '2021-03-21' );
For hour:
SELECT DATEPART(HOUR, '2021-03-21 08:50:30' );

Sql Server get current date time in Europe

SELECT GETDATE()
The above query in SQL Server will return current date and time in USA because server is located in USA. How can I modify it to retrieve current date and time in Europe?
try this: Set #Offset =
0 for Greenwich Mean Time (GMT) - Great Britain,
1 for Central European Time (CET) -Netherlands, Germnany, France
etc,
2 for Eastern European Time (EET) Czechoslovakia, Hungary, etc.
Set #Offset = 0, 1, 2 ...
Declare #offset tinyInt = 0
Select GetUtcDate() + #offset/24.0
Use SwitchDateTimeOffset function with the datetimeoffset data type (requires SQL Server 2008 or higher).
Demo query:
CREATE TABLE TimeZone (ID int identity,
LocalTime datetimeoffset);
INSERT INTO TimeZone values ('2008-05-21 17:50:01.1234567 -08:00'),
('2008-05-21 18:50:01.1234567 -08:00');
SELECT * FROM TimeZone;
SELECT ID, SWITCHOFFSET(LocalTime,'+01:00') [time for new time zone]
FROM TimeZone;
DROP TABLE TimeZone;
In your scenario this becomes:
SELECT SWITCHOFFSET(SYSDATETIMEOFFSET(),'+01:00')
As pointed out by p.campbell, you still have to decide which timezone represents 'Europe' for your purposes.

Convert datetime to specific format?

I want to convert a datetime to a specific format. The conversion should result in a variable of type datetime and not char or varchar. How do I do this in SQL server 2000, 2005 and 2008 ?
select CONVERT(varchar(30),getdate(),120)
I tried this, but it gives me a string. I want a datetime without the milli-seconds. SS 2012 has an option for this, but not previous versions.
http://blog.sqlauthority.com/2012/11/21/sql-server-display-datetime-in-specific-format-sql-in-sixty-seconds-033-video/
You can't have it both ways ... a variable of type "datetime" is defined as:
Defines a date that is combined with a time of day
with fractional seconds that is based on a 24-hour clock
You can CONVERT and DISPLAY in whatever format you choose, but the datetime data type will always have the milliseconds, even if you set them to zero.
You can remove the milliseconds from the datetime like this:
DATEADD(ms, -DATEPART(ms, date), date) > '2013-11-18 03:21:52'
Also check SQL Server Date Formats
or may be try like this to remove the millisecond part:-
declare #str datetime
set #str = '2013-11-18 17:24:05.784'
select convert(datetime, convert(char(19), #str, 126))

Time part of a DateTime Field in SQL

How would I be able to extract the time part of a DateTime field in SQL? For my project I have to return data that has a timestamp of 5pm of a DateTime field no matter what the date is
This will return the time-Only
For SQL Server:
SELECT convert(varchar(8), getdate(), 108)
Explanation:
getDate() is giving current date and time.
108 is formatting/giving us the required portion i.e time in this case.
varchar(8) gives us the number of characters from that portion.
Like:
If you wrote varchar(7) there, it will give you 00:00:0
If you wrote varchar(6) there, it will give you 00:00:
If you wrote varchar(15) there, it will still give you 00:00:00 because it is giving output of just time portion.
SQLFiddle Demo
For MySQL:
SELECT DATE_FORMAT(NOW(), '%H:%i:%s')
SQLFiddle Demo
In SQL Server if you need only the hh:mi, you can use:
DECLARE #datetime datetime
SELECT #datetime = GETDATE()
SELECT RIGHT('0'+CAST(DATEPART(hour, #datetime) as varchar(2)),2) + ':' +
RIGHT('0'+CAST(DATEPART(minute, #datetime)as varchar(2)),2)
If you want only the hour of your datetime, then you can use DATEPART() - SQL Server:
declare #dt datetime
set #dt = '2012-09-10 08:25:53'
select datepart(hour, #dt) -- returns 8
In SQL Server 2008+ you can CAST() as time:
declare #dt datetime
set #dt = '2012-09-10 08:25:53'
select CAST(#dt as time) -- returns 08:25:53
I know this is an old question, but since the other answers all
return strings (rather than datetimes),
rely on the internal representation of dates (conversion to float, int, and back) or
require SQL Server 2008 or beyond,
I thought I'd add a "pure" option which only requires datetime operations and works with SQL Server 2005+:
SELECT DATEADD(dd, -DATEDIFF(dd, 0, mydatetime), mydatetime)
This calculates the difference (in whole days) between date zero (1900-01-01) and the given date and then subtracts that number of days from the given date, thereby setting its date component to zero.
Try this in SQL Server 2008:
select *
from some_table t
where convert(time,t.some_datetime_column) = '5pm'
If you want take a random datetime value and adjust it so the time component is 5pm, then in SQL Server 2008 there are a number of ways. First you need start-of-day (e.g., 2011-09-30 00:00:00.000).
One technique that works for all versions of Microsoft SQL Server as well as all versions of Sybase is to use convert/3 to convert the datetime value to a varchar that lacks a time component and then back into a datetime value:
select convert(datetime,convert(varchar,current_timestamp,112),112)
The above gives you start-of-day for the current day.
In SQL Server 2008, though, you can say something like this:
select start_of_day = t.some_datetime_column
- convert(time, t.some_datetime_column ) ,
from some_table t
which is likely faster.
Once you have start-of-day, getting to 5pm is easy. Just add 17 hours to your start-of-day value:
select five_pm = dateadd(hour,17, t.some_datetime_column
- convert(time,t.some_datetime_column)
)
from some_table t
Note that from MS SQL 2012 onwards you can use FORMAT(value,'format')
e.g. WHERE FORMAT(YourDatetime,'HH:mm') = '17:00'
"For my project, I have to return data that has a timestamp of 5pm of a DateTime field, No matter what the date is."
So I think what you meant was that you needed the date, not the time. You can do something like this to get a date with 5:00 as the time:
SELECT CONVERT(VARCHAR(10), GetDate(), 110) + ' 05:00:00'
This should strip away the date part:
select convert(datetime,convert(float, getdate()) - convert(int,getdate())), getdate()
and return a datetime with a default date of 1900-01-01.
you can use CONVERT(TIME,GETDATE()) in this case:
INSERT INTO infoTbl
(itDate, itTime)
VALUES (GETDATE(),CONVERT(TIME,GETDATE()))
or if you want print it or return that time use like this:
DECLARE #dt TIME
SET #dt = CONVERT(TIME,GETDATE())
PRINT #dt
select cast(getdate() as time(0))
returns for example :- 15:19:43
replace getdate() with the date time you want to extract just time from!
SELECT DISTINCT
CONVERT(VARCHAR(17), A.SOURCE_DEPARTURE_TIME, 108)
FROM
CONSOLIDATED_LIST AS A
WHERE
CONVERT(VARCHAR(17), A.SOURCE_DEPARTURE_TIME, 108) BETWEEN '15:00:00' AND '15:45:00'
declare #datetime as datetime
set #datetime = getdate()
select cast(cast(#datetime as time) as varchar(8))
For year:
SELECT DATEPART(YEAR, '2021-03-21' );
For hour:
SELECT DATEPART(HOUR, '2021-03-21 08:50:30' );