简体   繁体   中英

java jodatime cannot get back to 1st after the end of month

I am writing a program which is supposed to return the date day by day. I am using DateTime.plusDays(1) but it return 32 of Feb after 31 of Jan. I have simplified my code as below.

public static void main(String[] args) {

        DateTime datetime = new DateTime(1900, 1, 31, 0, 0, 0);
        DateTimeFormatter fmt = DateTimeFormat.forPattern("YYYYMMDD");
        for (int i = 0; i < 10; i++) {
            System.out.println(datetime.toString(fmt));
            datetime = datetime.plusDays(1);
        }
    }

The result I got is

 19000131 19000232 19000233...... 

Could anyone please advise? Thanks in advance.

try using this with out joda time to get the same result ( with java standard calendar )

public static void main(String[] args) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(1900, 0, 31); // month is 0 based
    for (int i = 0; i < 10; i++) {
        System.out.println(String.format("%4d%02d%02d", calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH)));
        calendar.add(Calendar.DAY_OF_MONTH, 1);
    }
}

--UPDATE--

if u insisist on using joda, u can use this:

public static void main(String[] args) {
    DateTime datetime = new DateTime(1900, 1, 31, 0, 0, 0);
    for (int i = 0; i < 10; i++) {
        System.out.printf("%4d%02d%02d\n", datetime.getYear(), datetime.getMonthOfYear(), datetime.getDayOfMonth());
        datetime = datetime.plusDays(1);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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