简体   繁体   English

如何计算MySQL中几个月的两个日期之间的差异

[英]How to calculate difference between two dates in months in MySQL

I have two columns in a MySQL table: 我在MySQL表中有两列:

  • DateOfService (datetime) DateOfService(datetime)
  • BirthDate (date) 出生日期(日期)

I want to run a MySQL query that will provide date difference between these two fields in months. 我想运行一个MySQL查询,它将在几个月内提供这两个字段之间的日期差异。

How can I do this in a MySQL select query? 我如何在MySQL选择查询中执行此操作?

Thanks. 谢谢。

Have a look at the TIMESTAMPDIFF() function in MySQL. 看看MySQL中的TIMESTAMPDIFF()函数。

What this allows you to do is pass in two TIMESTAMP or DATETIME values (or even DATE as MySQL will auto-convert) as well as the unit of time you want to base your difference on. 这允许你做的是传递两个TIMESTAMPDATETIME值(甚至DATE因为MySQL将自动转换)以及你想要差异的时间单位。

You can specify MONTH as the unit in the first parameter: 您可以在第一个参数中指定MONTH作为单位:

SELECT TIMESTAMPDIFF(MONTH, '2012-05-05', '2012-06-04')
-- 0

SELECT TIMESTAMPDIFF(MONTH, '2012-05-05', '2012-06-05')
-- 1

SELECT TIMESTAMPDIFF(MONTH, '2012-05-05', '2012-06-15')
-- 1

SELECT TIMESTAMPDIFF(MONTH, '2012-05-05', '2012-12-16')
-- 7

It basically gets the number of months elapsed from the first date in the parameter list. 它基本上获取参数列表中从第一个日期开始经过的月数。 This solution accounts for the varying amount of days in each month (28,30,31) as well as leap years. 该解决方案考虑了每个月(28,30,31)和闰年的不同天数。


If you want decimal precision in the number of months elapsed, it's a little more complicated, but here is how you can do it: 如果你想要经过几个月的小数精度,它会有点复杂,但是你可以这样做:

SELECT 
  TIMESTAMPDIFF(MONTH, startdate, enddate) +
  DATEDIFF(
    enddate,
    startdate + INTERVAL
      TIMESTAMPDIFF(MONTH, startdate, enddate)
    MONTH
  ) /
  DATEDIFF(
    startdate + INTERVAL
      TIMESTAMPDIFF(MONTH, startdate, enddate) + 1
    MONTH,
    startdate + INTERVAL
      TIMESTAMPDIFF(MONTH, startdate, enddate)
    MONTH
  )

Where startdate and enddate are your date parameters, whether it be from two date columns in a table or as input parameters from a script: 其中startdateenddate是您的日期参数,无论是来自表中的两个日期列还是来自脚本的输入参数:

Examples: 例子:

With startdate = '2012-05-05' AND enddate = '2012-05-27':
-- Outputs: 0.7097

With startdate = '2012-05-05' AND enddate = '2012-06-13':
-- Outputs: 1.2667

With startdate = '2012-02-27' AND enddate = '2012-06-02':
-- Outputs: 3.1935

This could work: 这可能有效:

SELECT 12 * (YEAR(DateOfService) 
              - YEAR(BirthDate)) 
       + (MONTH(DateOfService) 
           - MONTH(BirthDate)) AS months 
FROM table

TRY with 尝试

PERIOD_DIFF(P1,P2) PERIOD_DIFF(P1,P2)

Returns the number of months between periods P1 and P2. 返回时段P1和P2之间的月数。 P1 and P2 should be in the format YYMM or YYYYMM . P1和P2的格式应为YYMMYYYYMM Note that the period arguments P1 and P2 are not date values. 请注意,句点参数P1和P2不是日期值。

mysql> SELECT PERIOD_DIFF(200802,200703); mysql> SELECT PERIOD_DIFF(200802,200703); -> 11 - > 11

试试这个:

SELECT DATEDIFF(DateOfService, BirthDate) / 30 as months FROM ...

TIMESTAMPDIFF(MONTH, Start_date, End_date)

例:

SELECT TIMESTAMPDIFF(MONTH, BirthDate, DateOfService) AS Months FROM Table

Based on a summary of all answers and a Google search, I think there are four almost similar ways to write it: 基于所有答案的摘要和Google搜索,我认为有四种几乎相似的方式来编写它:

1) 1)

TIMESTAMPDIFF(MONTH, Start_date, End_date) AS Period

Eg 例如

TIMESTAMPDIFF(MONTH, MIN(r.rental_date), MAX(r.rental_date)) AS Period

2) 2)

PERIOD_DIFF(date_format(now(), '%Y%m'), date_format(time, '%Y%m')) as months

Or 要么

PERIOD_DIFF(date_format(End_date(), '%Y%m'), date_format(Start_date, '%Y%m')) as months

Eg 例如

PERIOD_DIFF(date_format(MAX(r.rental_date), '%Y%m'), date_format(MIN(r.rental_date), '%Y%m')) as months

3) 3)

PERIOD_DIFF(EXTRACT(YEAR_MONTH FROM NOW()), EXTRACT(YEAR_MONTH FROM time)) AS months

OR 要么

PERIOD_DIFF(EXTRACT(YEAR_MONTH FROM End_date()), EXTRACT(YEAR_MONTH FROM Start_date)) AS months

Eg 例如

PERIOD_DIFF(EXTRACT(YEAR_MONTH FROM MAX(r.rental_date)), EXTRACT(YEAR_MONTH FROM MIN(r.rental_date))) as Months

4) 4)

PERIOD_DIFF(concat(year(d1),if(month(d1)<10,'0',''),month(d1)), concat(year(d2),if(month(d2)<10,'0',''),month(d2))) as Months**

Eg 例如

PERIOD_DIFF(
            concat(year(MAX(r.rental_date)),if(month(MAX(r.rental_date))<10,'0',''),month(MAX(r.rental_date))),
            concat(year(MIN(r.rental_date)),if(month(MIN(r.rental_date))<10,'0',''),month(MIN(r.rental_date)))
           ) as Months

The 'right' answer depends on exactly what you need. “正确”的答案完全取决于您的需求。 I like to round to the closest whole number . 我喜欢四舍五入到最接近的整数

Consider these examples: 1st January -> 31st January: It's 0 whole months, and almost 1 month long. 考虑这些例子:1月1日 - > 1月31日:整整0个月,差不多1个月。 1st January -> 1st February? 1月1日 - > 2月1日? It's 1 whole month, and exactly 1 month long. 整整1个月,恰好1个月。

To get the number of whole months, use: 要获得月的数量,请使用:

SELECT TIMESTAMPDIFF(MONTH, '2018-01-01', '2018-01-31');  => 0
SELECT TIMESTAMPDIFF(MONTH, '2018-01-01', '2018-02-01');  => 1

To get a rounded duration in months, you could use: 要获得几个月的圆形持续时间,您可以使用:

SELECT ROUND(TIMESTAMPDIFF(DAY, '2018-01-01', '2018-01-31')*12/365.24); => 1
SELECT ROUND(TIMESTAMPDIFF(DAY, '2018-01-01', '2018-01-31')*12/365.24); => 1

This is accurate to +/- 5 days and for ranges over 1000 years. 这精确到+/- 5天,范围超过1000年。 Zane's answer is obviously more accurate, but it's too verbose for my liking. Zane的答案显然更准确,但对我的喜好来说太冗长了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM