繁体   English   中英

如何在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?

我也想处理2月29日的leap年案件。

我尝试了以下操作,但是在将每种时间格式转换为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纪元以来的毫秒数,格式为irrlevent。

DatetoString方法仅使用本地系统来提供其内容的可读形式。 您不能修改此格式(直接也不应该修改,因为它将在您运行代码的下一台计算机上更改)

如果要以给定格式显示Date ,则应使用适当的格式化程序,例如...

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

日期 - 只有

克里斯·马丁答案是正确的。 如果不比较跨时区的日期的开始/结束,则可以将类用于仅日期,而没有任何时间或时区组成部分。

Joda-Timejava.time

除了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 );
}

暂无
暂无

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

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