41554

Find which nth occurrence of a day in a month for a date in Java

Question:

I need to find which nth dayOfWeek a particular day is in the month for a date in Java. For example, today is April 20th, 2016 which is the <strong>3rd</strong> Wednesday in the month or October 31, 2016 which is the <strong>5th</strong> Monday in October. How can I find which number the particular occurrence of a day is in the month?

Answer1:

Use the get method of the Calendar class.

public static int getOccurenceOfDayInMonth() { return Calendar.getInstance().get(Calendar.DAY_OF_WEEK_IN_MONTH); }

[EDIT]

Here is a solution given any date, rather than the current date.

public static int getOccurenceOfDayInMonth(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH); }

Recommend

  • Is it possible to set mySQL to have a saturday as the start of the week?
  • SpringBoot TestRestTemplate and LocalDateTime not working
  • Microdata and multiple opening in a day
  • Does this cron expression mean every other Sunday?
  • LINQ to Entities does not recognize the method
  • Javascript hide/show div based on the day of the week?
  • How many people are registering in the day of the week
  • PHP create range of dates
  • Count on the month
  • Count number of Mondays, Tuesdays etc from table using Linq
  • PHP/mysql: how do I display records sorted by time and grouped by date?
  • Full calendar business hour constrain on day click event
  • Need to understand - why CDATA section is treated as if the ?
  • How do you make a dynamically-sized data table?
  • PHP IntlDateFormatter wrong date/time conversion
  • Windows Azure Multi Tenancy
  • Dynamic Sieve Algorithms for Prime Generation
  • Drupal: create a node with employee working hours
  • How to get multiple substrings from string in Android/Java ?
  • keydown event triggered only once
  • Name of day in string format with days to furure
  • Is there any way to center certain columns in table?
  • regex, multiline extract in R
  • get helsinki local time regardless of local time zone
  • How to mock current date?
  • Get count of created entries for each day
  • jquery full calendar
  • Send emails through VB6 if no email client
  • Check for zero lines output from command over SSH
  • Array with custom indexes in Ionic2
  • Extracting HTML between tags
  • Is there a javascript serializer for JSON.Net?
  • Date difference with leap year
  • Where to put my custom functions in Wordpress?
  • Trying to switch camera back to front but getting exception
  • Buffer size for converting unsigned long to string
  • Free memory of cv::Mat loaded using FileStorage API
  • Angular 2 constructor injection vs direct access
  • Programmatically clearing map cache
  • Binding checkboxes to object values in AngularJs