在不使用库的情况下遍历日期范围-Java

在不使用库的情况下遍历日期范围-Java,java,date,calendar,Java,Date,Calendar,嗨,我想在不使用任何库的情况下遍历一个日期范围。我希望从2005年1月18日开始(希望将其格式设置为yyyy/M/d),并以天为间隔进行迭代,直到当前日期。我已经格式化了开始日期,但我不知道如何将其添加到日历对象并进行迭代。我想知道是否有人能帮忙。谢谢 String newstr = "2005/01/18"; SimpleDateFormat format1 = new SimpleDateFormat("yyyy/M/d"); 使用SimpleDateFormat将字符串解析为Date对象

嗨,我想在不使用任何库的情况下遍历一个日期范围。我希望从2005年1月18日开始(希望将其格式设置为yyyy/M/d),并以天为间隔进行迭代,直到当前日期。我已经格式化了开始日期,但我不知道如何将其添加到日历对象并进行迭代。我想知道是否有人能帮忙。谢谢

String newstr = "2005/01/18";
SimpleDateFormat format1 = new SimpleDateFormat("yyyy/M/d");

使用
SimpleDateFormat
将字符串解析为
Date
对象,或将
Date
对象格式化为字符串

使用class
Calendar
进行日期运算。它有一个
add
方法来推进日历,例如以天为单位

请参阅上述类的API文档


或者,使用库,这会使这些事情变得更容易。(标准Java API中的
Date
Calendar
类存在许多设计问题,功能不如Joda Time强大)。

Java,事实上许多系统,自1970年1月1日UTC上午12:00起将时间存储为毫秒数。此数字可以定义为长字符

//to get the current date/time as a long use
long time = System.currentTimeMillis();

//then you can create a an instance of the date class from this time.
Date dateInstance = new Date(time);

//you can then use your date format object to format the date however you want.
System.out.println(format1.format(dateInstance));

//to increase by a day, notice 1000 ms = 1 second, 60 seconds = 1 minute,
//60 minutes = 1 hour 24 hours = 1 day so add 1000*60*60*24 
//to the long value representing time.
time += 1000*60*60*24;

//now create a new Date instance for this new time value
Date futureDateInstance = new Date(time);

//and print out the newly incremented day
System.out.println(format1.format(futureDateInstance));

这不是一个好方法来增加一天的日期。由于DST,当一天持续25小时时,它每年至少会失败一次。这只是一个如何增加时间的示例,而不是endall固定解决方案。如果需要,您可以考虑更多因素并重新实现GregorianCalendar?不,对不起。数据运算很难正确地进行。这确实是你不想自己做的事情。但他要求一种不使用库的方法,我想他想了解它是如何工作的。所以日期不是库的一部分,但日历是?它们在同一个包中,都在JDK中。
//to get the current date/time as a long use
long time = System.currentTimeMillis();

//then you can create a an instance of the date class from this time.
Date dateInstance = new Date(time);

//you can then use your date format object to format the date however you want.
System.out.println(format1.format(dateInstance));

//to increase by a day, notice 1000 ms = 1 second, 60 seconds = 1 minute,
//60 minutes = 1 hour 24 hours = 1 day so add 1000*60*60*24 
//to the long value representing time.
time += 1000*60*60*24;

//now create a new Date instance for this new time value
Date futureDateInstance = new Date(time);

//and print out the newly incremented day
System.out.println(format1.format(futureDateInstance));