Java生成x和y之间的所有日期 [英] Java Generate all dates between x and y

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

问题描述

我尝试生成日期x和日期y之间的日期范围,但失败了。我在C#中使用相同的方法,因此我尝试了尽可能多的修改,但未能获得结果。知道我可以解决什么问题吗?

I attempted to generate the date range between date x and date y but failed. I have the same method in c# so I tried to modify it as much as I can but failed to get result. Any idea what I could fix?

private ArrayList<Date> GetDateRange(Date start, Date end) {
    if(start.before(end)) {
        return null;
    }

    int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
    ArrayList<Date> listTemp = new ArrayList<Date>();
    Date tmpDate = start;

    do {
        listTemp.add(tmpDate);
        tmpDate = tmpDate.getTime() + MILLIS_IN_DAY;
    } while (tmpDate.before(end) || tmpDate.equals(end));

    return listTemp;
}

说实话,我试图将所有日期从1月1日开始,一直到2012年底,即12月31日。如果有更好的方法,请告诉我。
谢谢

To be honest I was trying to get all the dates starting from january 1st till the end of year 2012 that is december 31st. If any better way available, please let me know. Thanks

推荐答案

Joda-Time



日历和Java中的日期API确实很奇怪...我强烈建议考虑使用jodatime,这是处理日期的实际库。
它确实功能强大,如快速入门所示: http:// joda- time.sourceforge.net/quickstart.html

此代码通过使用 Joda-Time

import java.util.ArrayList;
import java.util.List;

import org.joda.time.DateTime;


public class DateQuestion {

    public static List<DateTime> getDateRange(DateTime start, DateTime end) {

        List<DateTime> ret = new ArrayList<DateTime>();
        DateTime tmp = start;
        while(tmp.isBefore(end) || tmp.equals(end)) {
            ret.add(tmp);
            tmp = tmp.plusDays(1);
        }
        return ret;
    }

    public static void main(String[] args) {

        DateTime start = DateTime.parse("2012-1-1");
        System.out.println("Start: " + start);

        DateTime end = DateTime.parse("2012-12-31");
        System.out.println("End: " + end);

        List<DateTime> between = getDateRange(start, end);
        for (DateTime d : between) {
            System.out.println(" " + d);
        }
    }
}

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

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