迭代列表对象中的日期变量并根据位置选择日期范围

我有一种情况,我在List. 现在,我想选择前 2 个位置日期作为开始日期和结束日期,然后选择下 2 个位置作为开始日期和结束日期,依此类推。获得开始日期和结束日期后,我需要找到天数之间的天数并计算天数。

这是列表对象中的日期。

[2018-09-05, 2018-09-14, 2018-09-29, 2018-10-14, 2018-10-29]

  1. 2018-09-05作为开始2018-09-13日期和结束日期 - 查找这些日期之间的天数。

  2. 2018-09-14作为开始2018-09-28日期和结束日期 - 查找这些日期之间的天数。

  3. 2018-09-29作为开始2018-10-13日期和结束日期 - 查找这些日期之间的天数。

  4. 2018-10-14作为开始2018-10-28日期和结束日期 - 查找这些日期之间的天数。

请帮我如何找到它。提前致谢。


www说
浏览 210回答 2
2回答

慕哥9229398

如果列表包含偶数个有效日期字符串,则以下代码将起作用。将迭代列表,提取每对日期并计算天数差异:public static long getDaysDif(LocalDate fromDate, LocalDate toDate) {&nbsp; &nbsp; return ChronoUnit.DAYS.between(fromDate, toDate);}public static LocalDate getLocalDateFromString(String d, String format) {&nbsp; &nbsp; return LocalDate.parse(d, DateTimeFormatter.ofPattern(format));}public static void main(String[] args) {&nbsp; &nbsp; List<String> list = new ArrayList<>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (Arrays.asList&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ("2018-09-05", "2018-09-13", "2018-09-14", "2018-09-28", "2018-09-29", "2018-10-13"));&nbsp; &nbsp; for (int i = 0; i < list.size(); i+=2) {&nbsp; &nbsp; &nbsp; &nbsp; String strStart = list.get(i);&nbsp; &nbsp; &nbsp; &nbsp; String strEnd = list.get(i + 1);&nbsp; &nbsp; &nbsp; &nbsp; LocalDate dateStart = getLocalDateFromString(strStart, "yyyy-MM-dd");&nbsp; &nbsp; &nbsp; &nbsp; LocalDate dateEnd = getLocalDateFromString(strEnd, "yyyy-MM-dd");&nbsp; &nbsp; &nbsp; &nbsp; long dif = getDaysDif(dateStart, dateEnd);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(dif);&nbsp; &nbsp; }}将打印:81414

PIPIONE

我不完全理解您关于选择日期的问题的第一部分,但要找到日期之间的天数,您可以执行以下操作:import java.time.LocalDate;import java.time.Period;public class Application {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; LocalDate startDate= LocalDate.now();&nbsp; &nbsp; &nbsp; &nbsp; LocalDate endDate= today.plusDays(6);&nbsp; &nbsp; &nbsp; &nbsp; Period period = Period.between(startDate, endDate);&nbsp; &nbsp; &nbsp; &nbsp; int difference = period.getDays();&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java