Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change only time part of a datetimeoffset in SQL

How can I set only the time portion of a SQL datetimeoffset variable?

For example:

DECLARE @date datetimeoffset = '2014-01-11 11:04:26 +02:00'

I want to calculate two further datetimeoffsets:

@startdate should be '2014-01-11 00:00:00 +02:00'
@enddate should be '2014-01-12 00:00:00 +02:00'

But all the solutions I tried set the offset to zero.

NOTE: I need the original offset in the results since I need to compare them to some datetimeoffset columns in a table. So just casting to a date will not work.

Further note: This would be quite easy in SQL2012; I could use DATETIMEOFFSETFROMPARTS. Unfortunately, I am not able to upgrade to 2012 at the moment. Example:

SET @startdate = SELECT DATETIMEOFFSETFROMPARTS(datepart(yyyy, @date), datepart(mm, @date), datepart(dd, @date), 0, 0, 0, 0, datepart(tz, @date), 0, 7);
like image 354
Kev Avatar asked Jan 13 '14 12:01

Kev


People also ask

How do I change the time zone in SQL?

Changing the database timezone SQL Server users typically fetch the local timezone by using the GETDATE() function with insert/update statements or as a default constraint for a datetime column in a select statement.

How can change time in DateTime field in SQL query?

To update with the current date and time: UPDATE table_name SET date_field = CURRENT_TIMESTAMP; To update with a specific date value: UPDATE table_name SET date_field = 'YYYY-MM-DD HH:MM:SS.

How can I get only time from DateTime in SQL?

How do you get just the time from a DateTime in SQL? SELECT GETDATE();– Output: 2019-03-31 08:12:08.600. SELECT CAST('2019–03–31 08:12:08.600' AS TIME)– Output: 08:12:08.6000000. SELECT CONVERT(VARCHAR(10), CAST('2019–03–31 08:12:08.600' AS TIME), 0)– Output: 8:12AM.


2 Answers

DECLARE @date DATETIMEOFFSET = '2014-01-11 11:04:26 +02:00'

SELECT TODATETIMEOFFSET(CAST(@date AS date),DATEPART(tz,@date))
SELECT TODATETIMEOFFSET(DATEADD(day,1,CAST(@date AS date)),DATEPART(tz,@date))
like image 90
Anon Avatar answered Nov 09 '22 02:11

Anon


DECLARE @date DATETIMEOFFSET = '2014-01-11 11:04:26 +02:00'

SELECT @date InputDate,
CONVERT(DATETIMEOFFSET,(CONVERT(VARCHAR(20),CONVERT(DATETIME,(CONVERT(DATETIME,CONVERT(DATE,@date)))) ) + ' ' + RIGHT(@date,6))) StartDate,
CONVERT(DATETIMEOFFSET,(CONVERT(VARCHAR(20),CONVERT(DATETIME,(CONVERT(DATETIME,CONVERT(DATE,DATEADD(day,1,@date))))) ) + ' ' + RIGHT(@date,6))) EndDate
like image 25
Kishore Avatar answered Nov 09 '22 01:11

Kishore