Click here to Skip to main content
15,666,844 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using java 8 date and time classes in my code. I can find year, month, day, hours, minutes and seconds, but I cannot find a method to find a number of days in a month.

Here is my code.
String oldestDateString = "2015-10-01 00:00:00";
String latestDateString = "2015-12-25 00:00:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime oldestDate = LocalDateTime.parse(oldestDateString, formatter);
LocalDateTime latestDate = LocalDateTime.parse(latestDateString, formatter);
int year = oldestDate.getYear();
int month = oldestDate.getMonthValue();
int day = oldestDate.getDayOfMonth();
int hours = oldestDate.getHour();
int minutes = oldestDate.getMinute();
int seconds = oldestDate.getSecond();

I also want to iterate through “oldestDate” to “latestDate”. How can I iterate through “oldestDate” to “latestDate” until the “oldestDate” reaches to “latestDate”?
Updated 14-Oct-15 19:51pm

1 solution

You can find the number of days in a month by creating a datetime object for the first day of the following month, and subtracting 1 day. That will then be adjusted by the class object to the last day of the previous month.

I'm not sure what you mean by How can I iterate through “oldestDate” to “latestDate” until the “oldestDate” reaches to “latestDate”. What exactly are you trying to achieve during the iteration?
Share this answer
hasnain_ahmad 15-Oct-15 5:30am    
Could you write code for finding the total number of days?
I want to loop through these dates so that i can increment the "oldestDate" until it reaches to "latestDate". I want some data to sort between these days and store it to an array.
Richard MacCutchan 15-Oct-15 5:43am    
Well, I could but you will learn much more by doing it yourself. See

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900