Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

513
Views
Java 8 Date API - Get total number of weeks in a month

I have a Kotlin function to get the total number of weeks in a month

Code

fun getTotalWeeksInMonth(instant: Instant): Int {
    val calendar = Calendar.getInstance()
    calendar.time = Date.from(instant)

    return calendar.getActualMaximum(Calendar.WEEK_OF_MONTH)
}

However this is using a mix of the old Java date/time APIs (Date and Calendar) and the new APIs (Instant)

How would I achieve the same result, using just the new APIs?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You can try something like this pair of lines:

YearMonth currentYearMonth = 
    YearMonth.now( 
        ZoneId.systemDefault() 
    )
;
int weeks = 
    currentYearMonth
    .atEndOfMonth()
    .get(
        WeekFields.ISO.weekOfMonth()
    )
;
over 4 years ago · Santiago Trujillo Report

0

You can evaluate the "week of month" of last day of this month, in java:

static int getTotalWeeksInMonth(Instant instant) {
    LocalDate localDate = LocalDate.ofInstant(instant, ZoneId.systemDefault());
    LocalDate lastDayOfMonth = localDate.withDayOfMonth(localDate.lengthOfMonth());
    int lastWeekOfMonth = lastDayOfMonth.get(WeekFields.ISO.weekOfMonth());
    return lastWeekOfMonth;
}
over 4 years ago · Santiago Trujillo Report

0

See if this fits you, be careful about what Zone you are actually passing, and about WeekFields.ISO, in some regions it may work fine, but in others it may not:

Instant now = Instant.now();

ZonedDateTime zonedNow = now.atZone(ZoneId.systemDefault());
ZonedDateTime monthEnd = zonedNow.with(TemporalAdjusters.lastDayOfMonth());

System.out.println(monthEnd.get(WeekFields.ISO.weekOfMonth()));
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!