简体   繁体   English

如何在java中迭代日期范围

[英]How to iterate over range of date in java

     SimpleDateFormat dateformat2 = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
    Date date = new Date();
    String d=dateformat2.format(date);

Now I want to iterate from current date to next 3 month date.I want to date format need to same.现在我想从当前日期迭代到下一个 3 个月的日期。我想日期格式需要相同。 Any suggestion?有什么建议吗?

I'm not entirely sure what you mean in your question, but I'm guessing it has to do with iterating over dates for 3 months.我不完全确定您在问题中的意思,但我猜这与迭代日期 3 个月有关。 If that is the case, you can try something like this:如果是这种情况,您可以尝试以下操作:

for(int i = 0; i < month; i++) {
    for(int j = 0; j < day; j++) {
        //do something...
}}

Just set month to be the amount of months to iterate over (in this case 3), and day to be the number of days per month.只需将月份设置为要迭代的月份数(在本例中为 3),将天设置为每月的天数。

If the months in question don't necessarily have a consistent amount of days each, then you can try something a little different like this:如果有问题的月份不一定每个月份都有一致的天数,那么您可以尝试一些不同的东西:

First set a variable to the days total to iterate.首先将变量设置为要迭代的总天数。 You can get at this by calculating from a set definition of days in each respective month.您可以通过根据每个月的一组天数定义进行计算来获得这一点。 Then just iterate over the days然后只是迭代几天

for(int i = 0; i < daysLeftToIterate; i++) {
    //do something...
}

Edit:编辑:

After looking into Calendar, I think there may be a way to use that efficiently to solve your issue.在查看日历后,我认为可能有一种方法可以有效地使用它来解决您的问题。 You can define a Calendar object in "lenient mode" as described on the API:您可以按照 API 中的描述以“宽松模式”定义日历对象:

"Calendar has two modes for interpreting the calendar fields, lenient and non-lenient. When a Calendar is in lenient mode, it accepts a wider range of calendar field values than it produces. When a Calendar recomputes calendar field values for return by get(), all of the calendar fields are normalized. For example, a lenient GregorianCalendar interprets MONTH == JANUARY, DAY_OF_MONTH == 32 as February 1." “日历有两种解释日历字段的模式,宽松和非宽松。当日历处于宽松模式时,它接受比它产生的更广泛的日历字段值。当日历重新计算日历字段值以通过 get( ),所有日历字段都被规范化。例如,宽松的 GregorianCalendar 将 MONTH == JANUARY, DAY_OF_MONTH == 32 解释为二月 1。”

By doing that, you can define to search over a set amount of days, instead of months.通过这样做,您可以定义搜索设定的天数,而不是数月。 For example, you can define the entire period of time as Month=January, Day=90, which would give the date of the 90th day in the year.例如,您可以将整个时间段定义为 Month=January, Day=90,这将给出一年中第 90 天的日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM