Mysql 日期计算相差年、月、周、日数整理

1、相差年数

SELECT
  NOW() 当前日期,
  DATE_ADD(NOW(), INTERVAL - 400 DAY) 历史日期,
  TIMESTAMPDIFF(
    YEAR,
    DATE_ADD(NOW(), INTERVAL - 400 DAY),
    NOW()
  ) AS 相差年;

2、相差月数 

SELECT
  NOW() 当前日期,
  DATE_ADD(NOW(), INTERVAL - 400 DAY) 历史日期,
  TIMESTAMPDIFF(
    MONTH,
    DATE_ADD(NOW(), INTERVAL - 400 DAY),
    NOW()
  ) AS 相差月;

3、相差周数 

SELECT
  NOW() 当前日期,
  DATE_ADD(NOW(), INTERVAL - 400 DAY) 历史日期,
  TIMESTAMPDIFF(
    WEEK,
    DATE_ADD(NOW(), INTERVAL - 400 DAY),
    NOW()
  ) AS 相差周;

4、相差天数 

整理了一下三种方式:

SELECT
  NOW() 当前日期,
  DATE_ADD(NOW(), INTERVAL - 400 DAY) 历史日期,
  TIMESTAMPDIFF(
    DAY,
    DATE_ADD(NOW(), INTERVAL - 400 DAY),
    NOW()
  ) AS 相差日;
SELECT
  TO_DAYS('2018-09-10') - TO_DAYS('2017-09-01') AS 相差天数;
SELECT
  DATEDIFF(NOW(), '2018-09-01') AS 相差天数;

 

你可能感兴趣的:(数据库使用与维护)