在Java中生成2个给定日期之间的所有日期 [英] Generating all days between 2 given dates in Java

查看:525
本文介绍了在Java中生成2个给定日期之间的所有日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取一系列日期,而我的输入是从/到结构。
所以我的输入是:

I'm trying to get an array of Dates, while my input is a 'from'/'to' structure. So my input is:

String date1 = "2014-01-01";
String date2 = "2014-05-01";

我的输出应该是一个数组列表,其所有日期都在date1和date2之间。
我已经找到了,但是我只能找到有关两个日期之间的差异的问题:

My output should be an Arraylist with all dates between date1 and date2. I've already looked for this, but I could only find questions about the difference between 2 dates:

SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";

try {
    Date date1 = myFormat.parse(inputString1);
    Date date2 = myFormat.parse(inputString2);
    long diff = date2.getTime() - date1.getTime();
    System.out.println ("Days: " + TimeUnit.DAYS.convert(diff,TimeUnit.MILLISECONDS));
} catch (ParseException e) {
e.printStackTrace();
}

有任何提示或建议吗?所有其他问题都针对iOS或SQL。

Any hints or suggestions? All other questions are for iOS or SQL.

推荐答案

看看JodaTime: http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html

Take a look at JodaTime: http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html

DateTime dateTime1 = new DateTime(date1);
DateTime dateTime2 = new DateTime(date2);

List<Date> allDates = new ArrayList();

while( dateTime1.before(dateTime2) ){
   allDates.add( dateTime1.toDate() );
   dateTime1 = dateTime1.plusDays(1);
}

这篇关于在Java中生成2个给定日期之间的所有日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆