How to find the total number of days in the month using LocalDateTime in Java 8?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hasnainahmad
    New Member
    • Mar 2015
    • 4

    #1

    How to find the total number of days in the month using LocalDateTime in Java 8?

    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.
    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”?
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    Well, I am not up-to-date with the latest java date-time libraries, as I am with GregorianCalend ar and Joda-Time, but I can tell you a general trick that works independent of any library.
    Number of days in February 2000:
    1. get date object for 1st March 2000.
    2. subtract one day.
    3. get the day of the resulting date.


    About your second question:
    iterate by using a for-loop starting with oldestDate and add one day in each step until you reach your latestDate.

    Comment

    Working...