java时间的一些操作

获取两个日期之间所有的日期列表

  • 方法一:使用Date方式直接操作
private static List<String> dateT(Date beginTime, Date endTime) {
    List<String> daysList = new ArrayList<String>();
    DateFormat format = new SimpleDateFormat("yyyy.MM.dd");
    Calendar tempStart = Calendar.getInstance();
    tempStart.setTime(beginTime);
    Calendar tempEnd = Calendar.getInstance();
    tempEnd.setTime(endTime);
    while (tempStart.before(tempEnd) || tempStart.compareTo(tempEnd) == 0) {
        daysList.add(format.format(tempStart.getTime()));
        tempStart.add(Calendar.DAY_OF_YEAR, 1);
    }
    return daysList;
}
  • 方法二:使用LocalDate方式操作
public static List<String> dateT(Date beginTime, Date endTime) {
    LocalDate beginDate = LocalDateTime.ofInstant(beginTime.toInstant(), ZoneId.systemDefault()).toLocalDate();
    LocalDate endDate = LocalDateTime.ofInstant(endTime.toInstant(), ZoneId.systemDefault()).toLocalDate();
    List<String> daysList = new ArrayList<String>();
    while (beginDate.isBefore(endDate) || beginDate.isEqual(endDate)) {
        daysList.add(beginDate.format(DateTimeFormatter.ofPattern("yyyy.MM.dd")));
        beginDate = beginDate.plusDays(1);
    }
    return daysList;
}

输入:beginTime:2019-11-03 13:00:00 endTime: 2019-11-05 12:00:00
希望输出结果是2019.11.03,2019.11.04,2019.11.05

输出方法一方法二
2019.11.032019.11.03
2019.11.042019.11.04
2019.11.05

从结果对比看方法一tempStart.add(Calendar.DAY_OF_YEAR, 1)是对tempStart时间进行24小时位移得到的时间,在位移两次之后得到时间2019-11-05 13:00:00;此时tempStart.after(tempEnd),简单的判断条件tempStart.before(tempEnd) || tempStart.compareTo(tempEnd) == 0不成立,如果要得到正确结果需要对结束时间做一些复杂判断
方法二LocalDate只比较日期,不必考虑同一天不同时间的问题兼容,beginDate.isBefore(endDate) || beginDate.isEqual(endDate)条件判断简单且更为直观

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值