英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论