获取两个时间之间的天数

    getdiffdate(stime, etime) {
      var diffdate = new Array();
      var i = 0;

      while (stime <= etime) {
        diffdate[i] = stime;

        var stime_ts = new Date(stime).getTime();

        var next_date = stime_ts + 24 * 60 * 60 * 1000;

        var next_dates_y = new Date(next_date).getFullYear() + "-";
        var next_dates_m =
          new Date(next_date).getMonth() + 1 < 10
            ? "0" + (new Date(next_date).getMonth() + 1) + "-"
            : new Date(next_date).getMonth() + 1 + "-";
        var next_dates_d =
          new Date(next_date).getDate() < 10
            ? "0" + new Date(next_date).getDate()
            : new Date(next_date).getDate();

        stime = next_dates_y + next_dates_m + next_dates_d;

        //增加数组key
        i++;
      }
 getdiffdate('2022-12-01', '2022-12-05')
//返回的数据   '2022-12-01','2022-12-02','2022-12-03','2022-12-04','2022-12-05'
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java中的Calendar类和Date类来获取两个时间之间天数。 以下是一个示例代码: ```java import java.util.Calendar; import java.util.Date; public class DateUtil { /** * 获取两个时间之间天数(头尾双算) * * @param startDate 开始时间 * @param endDate 结束时间 * @return 两个时间之间天数 */ public static int getDaysBetweenTwoDates(Date startDate, Date endDate) { if (startDate == null || endDate == null) { return 0; } Calendar startCalendar = Calendar.getInstance(); startCalendar.setTime(startDate); Calendar endCalendar = Calendar.getInstance(); endCalendar.setTime(endDate); // 将时间设置为0时0分0秒 startCalendar.set(Calendar.HOUR_OF_DAY, 0); startCalendar.set(Calendar.MINUTE, 0); startCalendar.set(Calendar.SECOND, 0); endCalendar.set(Calendar.HOUR_OF_DAY, 0); endCalendar.set(Calendar.MINUTE, 0); endCalendar.set(Calendar.SECOND, 0); // 计算两个日期之间天数 int days = 0; while (startCalendar.before(endCalendar)) { startCalendar.add(Calendar.DAY_OF_MONTH, 1); days++; } days++; // 头尾双算 return days; } } ``` 在上面的代码中,我们使用了Calendar类将日期设置为0时0分0秒,这是因为如果不设置,在计算两个日期之间天数时可能会出现误差。同时,我们使用while循环计算两个日期之间天数,并且在最后加上1,以便将结束日期也计算在内。 使用示例: ```java Date startDate = new Date(); // 假设开始时间为当前时间 Date endDate = new Date(System.currentTimeMillis() + 3 * 24 * 3600 * 1000L); // 假设结束时间为当前时间之后3天 int days = DateUtil.getDaysBetweenTwoDates(startDate, endDate); System.out.println("两个时间之间天数为:" + days); ``` 输出结果: ``` 两个时间之间天数为:4 ``` 可以看到,头尾都算上了,结果为4天。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值