简体   繁体   English

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

[英]Iterate through date ranges without using libraries - Java

Hi I want to iterate through a date range without using any libraries. 嗨,我想遍历日期范围而不使用任何库。 I want to start on 18/01/2005(want to format it to yyyy/M/d) and iterate in day intervals until the current date. 我想从2005年1月18日开始(想将其格式化为yyyy / M / d),并以天为间隔进行迭代,直到当前日期为止。 I have formatted the start date, but I dont know how I can add it to a calendar object and iterate. 我已经格式化了开始日期,但是我不知道如何将其添加到日历对象并进行迭代。 I was wondering if anyone can help. 我想知道是否有人可以提供帮助。 Thanks 谢谢

String newstr = "2005/01/18";
SimpleDateFormat format1 = new SimpleDateFormat("yyyy/M/d");
Date date = format1.parse(newstr);
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
while (someCondition(calendar)) {
    doSomethingWithTheCalendar(calendar);
    calendar.add(Calendar.DATE, 1);
}

Use SimpleDateFormat to parse a string into a Date object or format a Date object into a string. 使用SimpleDateFormat将字符串解析为Date对象或将Date对象格式化为字符串。

Use class Calendar for date arithmetic. 使用Calendar类进行日期算术。 It has an add method to advance the calendar, for example with a day. 它具有add方法来提前行进日历,例如一天。

See the API documentation of the classes mentioned above. 请参阅上述类的API文档。

Alternatively, use the Joda Time library, which makes these things easier. 或者,使用Joda Time库,这使这些事情变得更容易。 (The Date and Calendar classes in the standard Java API have a number of design issues and are not as powerful as Joda Time). (标准Java API中的DateCalendar类存在许多设计问题,并且不如Joda Time强大。)

Java, and in fact many systems, store time as the number of Milliseconds since 12:00am january first 1970 UTC. Java(实际上是许多系统)将时间存储为自1970年1月1日UTC时间12:00 am以来的毫秒数。 this number can be defined as a long. 此数字可以定义为long。

//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));

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

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