java根据起始与结束时间取相差几个月

private int getDifference(String start, String end) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String str1 = start.substring(0, 7);
        String str2 = end.substring(0, 7);
        Calendar bef = Calendar.getInstance();
        Calendar aft = Calendar.getInstance();
        try {
            bef.setTime(sdf.parse(str1));
            aft.setTime(sdf.parse(str2));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        
        int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
        int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12;
        return Math.abs(month + result);
    }

当前时间的上一个小时的起始时间结束时间,可以通过以下代码实现: ```java import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class Main { public static void main(String[] args) { LocalDateTime now = LocalDateTime.now(); // 获当前时间 LocalDateTime lastHourStart = now.minusHours(1).withMinute(0).withSecond(0).withNano(0); // 获上一个小时的起始时间 LocalDateTime lastHourEnd = now.minusHours(1).withMinute(59).withSecond(59).withNano(999999999); // 获上一个小时的结束时间 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); System.out.println("上一个小时的起始时间:" + formatter.format(lastHourStart)); System.out.println("上一个小时的结束时间:" + formatter.format(lastHourEnd)); } } ``` 以上代码中,我们首先通过 `LocalDateTime.now()` 方法获当前时间,然后使用 `minusHours(1)` 方法获上一个小时的时间,接着使用 `withMinute(0)` 方法将分钟设置为0,使用 `withSecond(0)` 方法将秒数设置为0,使用 `withNano(0)` 方法将纳秒数设置为0,以获上一个小时的起始时间。同理,使用 `withMinute(59)` 方法将分钟设置为59,使用 `withSecond(59)` 方法将秒数设置为59,使用 `withNano(999999999)` 方法将纳秒数设置为999999999,以获上一个小时的结束时间。最后,使用 `DateTimeFormatter` 对象将时间格式化为字符串输出。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值