1. 程式人生 > 實用技巧 >兩個時間段內的具體天數展示

兩個時間段內的具體天數展示

要求:

  時間:2019-01-01~~~~2019-01-05 取出改時間段內的具體天數。

  

  private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.CHINA);
 /**
     * 兩個時間點的天數
     * 引數畢傳
     *
     * @param starDate yyyy-MM-dd HH:mm
     * @param endDate  yyyy-MM-dd HH:mm
     * @return
     */
    public static List<String> getDateTime(String starDate, String endDate) {
        List<String> list = new ArrayList<>();

        // 開始--結束
        LocalDate localDate = LocalDate.parse(starDate.substring(0, 10), dateFormatter);
        long startTime = localDate.atStartOfDay().toInstant(ZoneOffset.of("+8")).toEpochMilli();

        LocalDate endLocalDate = LocalDate.parse(endDate.substring(0, 10), dateFormatter);
        long endTime = endLocalDate.atStartOfDay().toInstant(ZoneOffset.of("+8")).toEpochMilli();

        while (startTime <= endTime) {
            String str = dateFormatter.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(startTime), ZoneId.of("Asia/Shanghai")));
            list.add(str);
            startTime += (24 * 60 * 60 * 1000);
        }
        return list;
    }

  

測試:

public static void main(String[] args) {
      String starttime="2019-01-01";
      String endtime="2019-01-05";
        List<String> dateTime = DateUtil.getDateTime(starttime, endtime);

        System.out.println(JSONObject.toJSONString(dateTime));
    }

結果: