Reverse of DATE_ADD / INTERVAL in MySQL - mysql

In mysql, we can do the following for adding months:
SELECT DATE_ADD('2014-08-20', INTERVAL 13 MONTH); //Result: 2015-09-20
Is there any way to do the reversed operation ? Example:
SELECT DIFF_IN_MONTHS('2015-09-20', '2014-08-20') //Result: 13
Roundings due to day differences are not a problem for me.

The function TIMESTAMPDIFF does this:
SELECT TIMESTAMPDIFF(MONTH, '2015-09-20', '2014-08-20');
TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)
Returns datetime_expr2 – datetime_expr1, where datetime_expr1 and
datetime_expr2 are date or datetime expressions. One expression may be
a date and the other a datetime; a date value is treated as a datetime
having the time part '00:00:00' where necessary. The unit for the
result (an integer) is given by the unit argument

So you are wanting to get the difference in days between the 2 dates?
DATEDIFF('1015-09-20','2014-08-20')

Related

MYSQL appear error #1292 when delete record with in 7 day at 2021 first week

i got a problem for MySQL , last week , i get the error when run this MySQL script
delete from calendar.schedule
WHERE startdate >= DATE(NOW()) - 7 and status = 'ready'
it will display
#1292 - Incorrect datetime value: '20210100' for column 'startdate' at row 1" error .
my testing date is 2021/1/7 , if i change the Mysql script to
delete from calendar.schedule
WHERE startdate >= DATE(NOW()) - 6 and status = 'ready'
it will work normally. now, this code has no issues. but it will have bugs in the first week of the next year. anyone can help with this? Many Thanks!
Wilson
Your issue is with this expression:
DATE(NOW()) - 7
When you try to subtract 7 from a date, MySQL converts the date to its integer representation (in this case I presume it was 20210107) and then subtract 7 from it, giving 20210100. It then tries to compare this to a datetime column and fails, since 20210100 is not a valid date. The code works when you use 6 because you end up with 20210101, which is valid. What you should be doing instead is subtracting an interval (see the manual) so that you use date arithmetic, not integer arithmetic:
CURDATE() - INTERVAL 7 DAY
Note that CURDATE() is equivalent to DATE(NOW())
If you do date arithmetic with integers as you are doing, the date is converted to an integer in the format YYYYMMDD, and then the value is subtracted.
The problem is this can produce a result integer that is not a valid date.
For example if NOW() is '2021-01-10' as it is right now when I run that expression, then DATE('2021-01-10) - 10 evaluates as 20210110 - 10 which is 20210100.
But there is no date with 00 as the day. The subtraction should be 2020-12-31, right? But when doing integer subtraction, that's not what you get.
Solution: Use date arithmetic, not integer arithmetic. You can write date arithmetic in either of the following ways:
DATE('2021-01-10') - INTERVAL 10 DAY
DATE_SUB('2021-01-10', INTERVAL 10 DAY)

MYSQL TIMESTAMPDIFF function is not working

I am trying to use TIMESTAMPDIFF function in one of my queries and is making an headache for me.
TABLE
id | web_address | timeperiod | timeperiod_exp
1 | www.google.com | 1564692614 | 1564779014
1564692614 = GMT: Thursday, August 1, 2019 8:50:14 PM
1564779014 = GMT: Friday, August 2, 2019 8:50:14 PM
WHATS THE PROBLEM ?
As one can see the difference between these two timestamps is exactly 1 day but is returning no records.
SELECT * FROM mytable WHERE TIMESTAMPDIFF(DAY, timeperiod, timeperiod_exp) >= 1
WHERE IS THE FIDDLE ?
https://www.db-fiddle.com/f/udmrC2xdvrEEKGxEF7ty84/7
WHAT SHOULD BE DONE ?
Please take a look at the fiddle above and suggest what should be modified or other function in place of timestampdiff.
Look at the documentation for TIMESTAMPDIFF()
TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)
Returns datetime_expr2 − datetime_expr1, where datetime_expr1 and
datetime_expr2 are date or datetime expressions. One expression may be
a date and the other a datetime
As you see, it expects the parameters to be of type DATE or DATETIME. But you have your timestamps stored as integers.
So either use FROM_UNIXTIME() to convert your integer timestamps to DATETIME:
SELECT *
FROM mytable
WHERE TIMESTAMPDIFF(DAY, FROM_UNIXTIME(timeperiod), FROM_UNIXTIME(timeperiod_exp)) >= 1
db-fiddle
Or just use simple arithmetics (since we know how many seconds are in one day):
SELECT *
FROM mytable
WHERE (timeperiod_exp - timeperiod) >= 60*60*24
db-fiddle
As if i see the function TIMESTAMPDIFF() should take two timestamps but it is taking dates instead of direct timestamps in integers Thus the following works:
SELECT * FROM mytable WHERE TIMESTAMPDIFF(DAY, FROM_UNIXTIME(timeperiod), FROM_UNIXTIME(timeperiod_exp)) >= 1
Updated Fiddle
https://www.db-fiddle.com/f/udmrC2xdvrEEKGxEF7ty84/8

how to take the month difference of two dates in MySQL

how to take the month difference of two dates in MySQL.
I m trying to get the month difference of two dates but I'm getting no. of days.
select datediff('2014-10-17T00:00:00.000-07:00', '2015-02-06T00:00:00.000-08:00');
TIMESTAMPDIFF()
is your solution.
Syntax would be
TIMESTAMPDIFF(unit, datetime_expr1, datetime_expr2);
Returns datetime_expr2 − datetime_expr1, where datetime_expr1 and datetime_expr2 are date or datetime expressions. One expression may be a date and the other a datetime; a date value is treated as a datetime having the time part '00:00:00' where necessary.
~MySQL :: MySQL 5.5 Reference Manual :: 12.7 Date and Time Functions~
Legal values for unit
MICROSECOND (microseconds)
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
Examples
mysql> SELECT TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01');
-> 3
mysql> SELECT TIMESTAMPDIFF(YEAR,'2002-05-01','2001-01-01');
-> -1
mysql> SELECT TIMESTAMPDIFF(MINUTE,'2003-02-01','2003-05-01 12:05:55');
-> 128885
Please use this code
SELECT TIMESTAMPDIFF(MONTH, '2014-10-17T00:00:00.000-07:00','2015-02-06T00:00:00.000-08:00')
This could help,
SELECT 12 * (YEAR(STR_TO_DATE('01/01/2011', '%d/%m/%Y')) -
YEAR(STR_TO_DATE('01/01/2010', '%d/%m/%Y')))
+ (MONTH(STR_TO_DATE('01/01/2011', '%d/%m/%Y'))
- MONTH(STR_TO_DATE('01/01/2010', '%d/%m/%Y'))) AS months
Try this
Select PERIOD_DIFF(Date_format('2015-02-06T00:00:00.000-08:00', '%Y-%m'), Date_format('2014-10-17T00:00:00.000-07:00', '%Y%m'))
in MySQL server
DATEDIFF is built in function
You can get Difference of
Day
Month
Year
SELECT DATEDIFF(DAY,'2018-05-01',GetDate())
SELECT DATEDIFF(Month,'2018-05-01',GetDate())
SELECT DATEDIFF(Year,'2018-05-01',GetDate())

mysql and date comparison with date function and without

I notice a strange behavior for me when using date() and without:
when I use
SELECT * FROM `mytable` WHERE date(date_add) >= '2017-08-01' and date(date_add) <= '2017-08-31'
I get all dates records within the given date range but if do:
SELECT * FROM `mytable` WHERE date_add >= '2017-08-01' and date_add <= '2017-08-31'
I don't get the rows from the last day 31, why? (the date_add field is datetime type)
EDIT:
How should I code date range correctly? Because what I understand so far is that if I don't use full time like YYYY-MM-DD HH-MM-SS I should always compare with DATE() to avoid missing results from the last day.
That's because date_add is a DATETIME field. If the time for the date 2017-08-31 is something like 08:15:00 or 13:21:00 in your table, your date is "bigger" than just 2017-08-31 00:00:00. Your comparison would just return data for the 2017-08-31 having the time 00:00:00.
Because without the date() transformation your comparison imply the values '2017-08-01 00:00:00' and '2017-08-01 00:00:00'

DATEDIFF() Parameter Issue

The old DATEDIFF() allowed users to use 3 parameters, and I was trying to do this so I could get hours out of my DATEDIFF rather than days, (I'm trying to show hours since a post). In my database I'm using a TIMESTAMP and this line of code to pull a value, and obviously it doesn't work because I have the extra parameter. Once I remove the 'hour' or 'hh' the query runs and returns a value in days.
SELECT DATEDIFF(hour, CURDATE(), (SELECT Post_Date FROM Post_T WHERE pk_PostID = 1) )
Is there an easy way I can return the hourly value?
Also I'm using MYSQL Version 5.5.20.
Like it says in the documentation:
DATEDIFF(expr1,expr2)
DATEDIFF() returns expr1 – expr2 expressed as a value in days from one
date to the other. expr1 and expr2 are date or date-and-time
expressions. Only the date parts of the values are used in the
calculation.
If you want the result in hours you should use Timestampdiff
TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)
Returns datetime_expr2 – datetime_expr1, where datetime_expr1 and
datetime_expr2 are date or datetime expressions. One expression may be
a date and the other a datetime; a date value is treated as a datetime
having the time part '00:00:00' where necessary. The unit for the
result (an integer) is given by the unit argument.
The unit argument can be: MICROSECOND (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR.
In your case you can do:
SELECT TIMESTAMPDIFF(hour, CURDATE(), (SELECT Post_Date FROM Post_T WHERE pk_PostID = 1) )