如何在Java中迭代如下格式的日期范围25-12-2012到31-12-2012(应保留连字符)

How to iterate over a date range in the following format 25-12-2012 to 31-12-2012(hyphen should be maintained) in Java?

本文关键字:31-12-2012 25-12-2012 连字符 保留 范围 日期 Java 迭代 格式      更新时间:2023-09-26

我也想处理闰年2月29日的情况。

我尝试了以下方法,但在将每种时间格式转换为dd-mm-yyyy时遇到了麻烦。

GregorianCalendar gcal = new GregorianCalendar();
SimpleDateFormat sdfd = new SimpleDateFormat("dd-MM-yyyy");
Date start = sdfd.parse("26-02-1989");
Date end = sdfd.parse("06-03-1989");
gcal.setTime(start);
while (gcal.getTime().before(end)) 
{
    gcal.add(Calendar.DAY_OF_YEAR, 1);
    System.out.println( gcal.getTime().toString());
    System.out.println(gcal.);
}

我也可以在Java中使用Javascript引擎

java.util.Date是错误的类型。它具有毫秒(不是天)精度。java.time.LocalDate比较合适。如果您需要Java <8兼容性,请使用ThreeTen。

格式化LocalDate:

localDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))

Date对象只是一个容器,用于表示自Unix纪元以来的毫秒数,格式无关紧要。

DatetoString方法只是使用系统本地提供其内容的人类可读表示。你不能修改这个格式(你也不应该直接修改,因为它会在下一台你运行代码的机器上改变)

如果您想以给定的格式显示Date,那么您应该使用适当的格式化程序,例如…

System.out.println( sdfd.format(gcal.getTime()));

仅限日期

Chris Martin的答案是正确的。如果您没有跨时区比较天的开始/结束,那么您可以使用仅用于日期的类,而不需要任何时间或时区组件。

Joda-Time &java.time h1> 了java。java.time包,你可以使用受java.time启发的Joda-Time。java。time和Joda-Time提供LocalDate课程。这两个框架都有各自的优点和缺点。如果你小心使用import语句,你可以在一个项目中使用这两个框架。 示例代码

Joda-Time 2.3中的示例代码。

DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MM-yyyy" );
// LocalDate start = formatter.parseLocalDate( "26-02-1989" );
LocalDate start = new LocalDate( 1989, 2, 26 );
LocalDate stop = new LocalDate( 1989, 3, 6 );
LocalDate localDate = start;
while ( localDate.isBefore( stop ) )
{
    String output = formatter.print( localDate );
    localDate = localDate.plusDays( 1 );
}