如何在Java中通过增加日期来比较两个日期?

huangapple go评论102阅读模式
英文:

How to compare two dates in Java by incrementing Date?

问题

String dt = "2008-01-01";  // 开始日期
String et = "2008-01-10";

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
Date startDate = sdf.parse(dt);
Date endDate = sdf.parse(et);
Date incDate;
// dt 现在是新日期

do {
    System.out.println("嘿,我被调用了......");
    
    c.setTime(sdf.parse(dt));
    c.add(Calendar.DATE, 1);  // 要添加的天数
    dt = sdf.format(c.getTime());
    System.out.println("增加的日期:" + dt);
    incDate = sdf.parse(dt);
} while (endDate.compareTo(incDate) >= 0);
英文:

How to compare two dates in Java by incrementing Date?

String dt = "2008-01-01";  // Start date
String et="2008-01-10";

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
Date startDate=sdf.parse(dt);
Date  endDate=sdf.parse(et);
Date incDate;
// dt is now the new date

do
{
    System.out.println("hey i am called.....");
    
    c.setTime(sdf.parse(dt));
    c.add(Calendar.DATE, 1);  // number of days to add
    dt = sdf.format(c.getTime());
    System.out.println("Incremet Date"+dt);
    incDate=sdf.parse(dt);
}
while(endDate.compareTo(incDate)>=0);

答案1

得分: 1

首先,您应该开始使用像@TomStroemer指出的较新类。

我认为您想要获取两个日期之间的天数?

LocalDate startDate = LocalDate.parse("2008-01-01");
LocalDate endDate = LocalDate.parse("2008-01-10");

Period period = Period.between(startDate, endDate);

System.out.println(period.getDays());

应该输出8,因为它们之间有8天。尚未测试该代码。

请查阅以下文档:
Period: https://docs.oracle.com/javase/8/docs/api/java/time/Period.html
LocalDate: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html

同时请提供更多细节。

英文:

first you should start using the newer classes like @TomStroemer pointed out.

I think you want to get the number of days between the two dates ?

LocalDate startDate = LocalDate.parse("2008-01-01");
LocalDate endDate = LocalDate.parse("2008-01-10");

Period period = Period.between(startDate, endDate);

System.out.println(period.getDays());

Should print 8 because there are 8 days between. Haven't tested that code.

See the following docs:
Period: https://docs.oracle.com/javase/8/docs/api/java/time/Period.html
LocalDate: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html

And really provide more details.

huangapple
  • 本文由 发表于 2020年8月18日 20:23:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63468522.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定