Ilija Petkovic
Ilija Petkovic

Reputation: 143

Add N hours to MySQL datetime representation

How can I add N more hours to MySQL datetime representation? For example Current: 2013-12-01 19:30:13 (or I can get it with date("Y-m-d H:i:s") in PHP)

How can I get this: 2013-12-01 22:30:13 (adding 3 more hours)?

date("Y-m-d H:i:s") + 3 isn't working in PHP

Upvotes: 1

Views: 1593

Answers (3)

Jason Heo
Jason Heo

Reputation: 10246

It depends on where you want to do it.

in mysql

SELECT NOW() + INTERVAL 3 HOUR

SELECT CAST('2013-12-01 23:49:09' AS DATETIME) + INTERVAL 3 HOUR

in php

Date("Y-m-d h:i:s", time() + 3600 * 3)

Upvotes: 1

Filipe Silva
Filipe Silva

Reputation: 21657

In MySQL you can use date_add

From the docs:

DATE_ADD(date,INTERVAL expr unit)

These functions perform date arithmetic. The date argument specifies the starting date or datetime value. expr is an expression specifying the interval value to be added or subtracted from the starting date. expr is a string; it may start with a “-” for negative intervals. unit is a keyword indicating the units in which the expression should be interpreted.

The INTERVAL keyword and the unit specifier are not case sensitive.

For your case you can do:

date_add(now(), interval 3 HOUR)

sqlfiddle demo

Upvotes: 1

Przemysław Kalita
Przemysław Kalita

Reputation: 2017

in PHP:

$new_time = date("Y-m-d H:i:s", strtotime('+3 hours');

Upvotes: 1

Related Questions