Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not understanding mysql statement DATE_ADD(NOW() INTERVAL)

Tags:

php

mysql

I am working on a page which contains the following line of mysql. The overal objective is simply to match the current week num to the current date

$sql = "select distinct weekNum from " . DB_PREFIX . "schedule where DATE_ADD(NOW(), INTERVAL " . SERVER_TIMEZONE_OFFSET . " HOUR)"

As per my research DATE_ADD() allows you to add a certain number of days to a date.

Thus I am assuming DATE_ADD(NOW() adds the current date to...well date?

What exactly does INTERVAL do in this statment.

Any help interms of an explanation clarifying above statment will be much appreciated.

like image 826
Timothy Coetzee Avatar asked Dec 29 '17 07:12

Timothy Coetzee


People also ask

What is Date_add in MySQL?

The DATE_ADD() function adds a time/date interval to a date and then returns the date.

What is interval in MySQL?

MySQL INTERVAL() function returns the index of the argument that is more than the first argument. Syntax: INTERVAL(N,N1,N2,N3,...) It returns 0 if 1st number is less than the 2nd number and 1 if 1st number is less than the 3rd number and so on or -1 if 1st number is NULL. All arguments are treated as an integer.

How use now function in MySQL?

MySQL NOW() Function The NOW() function returns the current date and time. Note: The date and time is returned as "YYYY-MM-DD HH-MM-SS" (string) or as YYYYMMDDHHMMSS. uuuuuu (numeric).

How add days to now in MySQL?

INSERT INTO yourTableName VALUES(DATE_ADD(now(),interval n day)); In the above syntax, you can use curdate() instead of now(). The curdate() will store only date while now() will store both date and time.


1 Answers

DATE_ADD(NOW(), INTERVAL 2 HOURS)

-- This will add 2 hours to the current time

-- The format is DATE_ADD(date, INTERVAL value unit)

value can be anything --> a number

unit will be -- > anything from following list

MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
SECOND_MICROSECOND
MINUTE_MICROSECOND
MINUTE_SECOND
HOUR_MICROSECOND
HOUR_SECOND
HOUR_MINUTE
DAY_MICROSECOND
DAY_SECOND
DAY_MINUTE
DAY_HOUR
YEAR_MONTH

So you can add minutes , Hours , months into your date using this function

Like that you can use the function DATE_SUB(date, INTERVAL value unit) Which will substract the date hope you are clear. for more information just visit the link [https://www.w3schools.com/sql/func_mysql_date_add.asp]

like image 101
Pranav Deshpande Avatar answered Sep 26 '22 08:09

Pranav Deshpande