简体   繁体   English

如何处理两个日期变量设置的上限和下限内的日期范围

[英]How to do processing for a range of dates which are within the upper and lower limit set by 2 date variables

I have with me 2 dates in different date variables in a java desktop application. 我在Java桌面应用程序中的不同日期变量中有2个日期。 Now I want to create a loop that does some processing for each date within these 2 dates. 现在,我想创建一个循环,对这两个日期中的每个日期进行一些处理。 (Excluding scenario where date= Upper bound value of date but including scenario where date=lower bound value of date). (不包括日期=日期上限值的方案,但包括日期=日期下限值的方案)。

I do understand basic usage of dates in java, I just want to know, is there any easy way of looping through all dates between these 2 dates, and then do some processing for each date? 我只是想知道Java中日期的基本用法,是否有任何简单的方法可以循环遍历这两个日期之间的所有日期,然后对每个日期进行一些处理?

Another question related to dates- how do I obtain only the current system date in java, as well as the year portion of a date variable (For getting year portion of a date do I have to put the entire value of date variable into a string variable and then extract relevant portion that represents year?) 与日期有关的另一个问题-如何仅获取Java中的当前系统日期以及日期变量的年份部分(要获取日期的年份部分,我必须将date变量的整个值放入字符串中变量,然后提取代表年份的相关部分?)

Here is a sample: http://helpdesk.objects.com.au/java/how-can-i-iterate-through-all-dates-in-a-range 这是一个示例: http : //helpdesk.objects.com.au/java/how-can-i-iterate-through-all-dates-in-a-range

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

public class DateIterator
   implements Iterator<Date>, Iterable<Date>
{

    private Calendar end = Calendar.getInstance();
    private Calendar current = Calendar.getInstance();

    public DateIterator(Date start, Date end)
    {
        this.end.setTime(end);
        this.end.add(Calendar.DATE, -1);
        this.current.setTime(start);
        this.current.add(Calendar.DATE, -1);
    }

    public boolean hasNext()
    {
        return !current.after(end);
    }

    public Date next()
    {
        current.add(Calendar.DATE, 1);
        return current.getTime();
    }

    public void remove()
    {
        throw new UnsupportedOperationException(
           "Cannot remove");
    }

    public Iterator<Date> iterator()
    {
        return this;
    }

    public static void main(String[] args)
    {
        Date d1 = new Date();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 22);
        Date d2 = cal.getTime();

        Iterator<Date> i = new DateIterator(d1, d2);
        while(i.hasNext())
        {
            Date date = i.next();
            System.out.println(date);
        }
    }
}

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

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