Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL convert datetime and subtract hours

Tags:

I am trying to convert a datetime (createTime) field from its default 2012-10-06 02:29:37.243 format to am/pm so I use

convert(varchar, CreateTime, 100) as CreateTime

and get Oct 6 2012 4:29AM.

So far so good but in the same statement I want to subtract 4 hours and then display the field (GMT issues).

I have gone through some posts here but could not find anything that can do it in single statement.

like image 743
bobsingh1 Avatar asked Oct 06 '12 04:10

bobsingh1


People also ask

How do I subtract two hours from a datetime in SQL?

MySQL SUBTIME() Function The SUBTIME() function subtracts time from a time/datetime expression and then returns the new time/datetime.

How do you subtract time in SQL?

Time subtraction: result = time1 - time2 If MINUTE( TIME2 ) <= MINUTE( TIME1 ) then MINUTE( RESULT ) = MINUTE( TIME1 ) - MINUTE( TIME2 ) . If MINUTE( TIME2 ) > MINUTE( TIME1 ) then MINUTE( RESULT ) = 60 + MINUTE( TIME1 ) - MINUTE( TIME2 ) and HOUR( TIME2 ) is incremented by 1.

Can you subtract from a date in SQL?

SQL Server DATEDIFF() FunctionThe DATEDIFF() function returns the difference between two dates.


2 Answers

declare @createTime datetime = '2012-10-06 02:29:37.243';

-- original value, default formatting
select @createTime;

-- formatted
select convert(varchar, @createTime, 100);

-- subtract 4 hours, formatted
select convert(varchar, dateadd(hour, -4, @createTime), 100);

The query above that uses dateadd will always subtract 4 hours. If your goal is to convert an arbitrary datetime from UTC to local time, then it's more complicated because the offset that you need to add/subtract depends on the original datetime. A single value like -4 won't always work. Here are some ideas for dealing with the general case:

Effectively Converting dates between UTC and Local (ie. PST) time in SQL 2005

like image 194
cbranch Avatar answered Nov 15 '22 13:11

cbranch


For People Who wants to subtract days and hours

    declare @createTime datetime = '2012-10-06 02:29:37.243';
select @createtime as originaltime, dateadd(day, -4, dateadd(hour,-1,@createtime))as minus4daysandhour
like image 21
mzonerz Avatar answered Nov 15 '22 13:11

mzonerz