java计算两个日期相差月数

本文介绍了一种使用Java计算两个日期间月份数的方法,并提供了一个存在局限性的示例代码。此外,还展示了如何利用SQL语句来计算两个日期间的月份数及天数,包括获取当前日期等实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.计算两个日期相差月数,不满一月按一月算 (方法存在问题,待处理)

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
 
 public static void main(String[] args) throws ParseException {
        System.out.println(getMonthSpace("2020-09-29", "2020-10-27"));

    }

/**
  * 获取两个日期相差多少个月
  */

    public static int getMonthSpace(String date1, String date2)
            throws ParseException {

        int result = 0;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();

        c1.setTime(sdf.parse(date1));
        c2.setTime(sdf.parse(date2));

      int i = c2.get(Calendar.YEAR)-c1.get(Calendar.YEAR);
        int month = 0;
        if (i<0)
        {
            month = -i*12;
        }else if(i>0)
        {
            month =  i*12;
        }
        result = (c2.get(Calendar.MONDAY) - c1.get(Calendar.MONTH)) + month;
        
        return result == 0 ? 1 : Math.abs(result);

    }

在这里插入图片描述
2.sql语句计算两个日期时间差

select now()  获取当前日期  年月日 时分秒
select curdate()  获取当前日期  只有年月日
select curtime() 获取当前日期  只有时分秒

计算两个指定日期的月差

SELECT TIMESTAMPDIFF(month,'2020-02-29','2020-04-01') AS DiffDate

在这里插入图片描述
计算指定日期与当前日期月差

 SELECT TIMESTAMPDIFF(month,'2020-02-28',(select curdate())) AS DiffDate

在这里插入图片描述
计算天的

SELECT DATEDIFF('2008-12-29','2008-12-28') AS DiffDate

在这里插入图片描述

记录一个方法

			Date creditDate = new Date();
                //格式化日期的对象(转化成习惯的时间格式)
            SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
            String date_out = formatter.format(creditDate).toString();
           

formatter.format()这个方法可以将日期转换为指定格式
Sun Feb 28 00:00:00 CST 2020 这样格式也可以进行转换

十二个月的日期
SELECT a.price,b.time2 from  
(select original_value as price,FROM_UNIXTIME( UNIX_TIMESTAMP(c.create_time),'%m' ) as mon 
from asset_info c where  FROM_UNIXTIME( UNIX_TIMESTAMP(c.create_time),'%Y' ) = '2020' GROUP BY mon) a 
RIGHT JOIN (SELECT '01' as time2 from  DUAL UNION ALL  
SELECT '02' as time2 from  DUAL UNION ALL 
SELECT '03' as time2 from  DUAL UNION ALL 
SELECT '04' as time2 from  DUAL UNION ALL 
SELECT '05' as time2 from  DUAL UNION ALL 
SELECT '06' as time2 from  DUAL UNION ALL 
SELECT '07' as time2 from  DUAL UNION ALL 
SELECT '08' as time2 from  DUAL UNION ALL 
SELECT '09' as time2 from  DUAL UNION ALL 
SELECT '10' as time2 from  DUAL UNION ALL 
SELECT '11' as time2 from  DUAL UNION ALL 
SELECT '12' as time2 from  DUAL )b on a.mon = b.time2
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值