<p>I am working on a project where the requirement is to have a date calculated as being the last Friday of a given month.  I think I have a solution that only uses standard Java, but I was wondering if anyone knew of anything more concise or efficient. Below is what I tested with for this year:</p>

<pre><code>    for (int month = 0; month &lt; 13; month++) {
        GregorianCalendar d = new GregorianCalendar();
        d.set(d.MONTH, month);
        System.out.println("Last Week of Month in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + d.getLeastMaximum(d.WEEK_OF_MONTH));
        d.set(d.DAY_OF_WEEK, d.FRIDAY);
        d.set(d.WEEK_OF_MONTH, d.getActualMaximum(d.WEEK_OF_MONTH));
        while (d.get(d.MONTH) &gt; month || d.get(d.MONTH) &lt; month) {
            d.add(d.WEEK_OF_MONTH, -1);
        }
        Date dt = d.getTime();
        System.out.println("Last Friday of Last Week in  " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + dt.toString());
    }
</code></pre>

[{'answer_id': 76265, 'author': 'scubabbl', 'author_id': 9450, 'author_profile': 'https://Stackoverflow.com/users/9450', 'pm_score': 0, 'selected': False, 'text': "<p>That looks like a perfectly acceptable solution. If that works, use it. That is minimal code and there's no reason to optimize it unless you have to. </p>\n"}, {'answer_id': 76389, 'author': 'Binil Thomas', 'author_id': 3973, 'author_profile': 'https://Stackoverflow.com/users/3973', 'pm_score': 1, 'selected': False, 'text': '<p>Slightly easier to read, brute-force approach:</p>\n\n<pre><code>public int getLastFriday(int month, int year) {\n    Calendar cal = Calendar.getInstance();\n    cal.set(year, month, 1, 0, 0, 0); // set to first day of the month\n    cal.set(Calendar.MILLISECOND, 0);\n\n    int friday = -1;\n    while (cal.get(Calendar.MONTH) == month) { \n        if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) { // is it a friday?\n            friday = cal.get(Calendar.DAY_OF_MONTH);\n            cal.add(Calendar.DAY_OF_MONTH, 7); // skip 7 days\n        } else {\n            cal.add(Calendar.DAY_OF_MONTH, 1); // skip 1 day\n        }\n    }\n    return friday;\n}\n</code></pre>\n'}, {'answer_id': 76430, 'author': 'Hans Doggen', 'author_id': 9504, 'author_profile': 'https://Stackoverflow.com/users/9504', 'pm_score': 3, 'selected': False, 'text': '<p>I would use a library like <a href="http://joda-time.sourceforge.net" rel="noreferrer">Jodatime</a>. It has a very useful API and it uses normal month numbers. And best of all, it is thread safe.</p>\n\n<p>I think that you can have a solution with (but possibly not the shortest, but certainly more readable):</p>\n\n<pre><code>DateTime now = new DateTime();      \nDateTime dt = now.dayOfMonth().withMaximumValue().withDayOfWeek(DateTimeConstants.FRIDAY);\nif (dt.getMonthOfYear() != now.getMonthOfYear()) {\n  dt = dt.minusDays(7);\n}       \nSystem.out.println(dt);\n</code></pre>\n'}, {'answer_id': 76437, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>You never need to loop to find this out.  For determining the "last Friday" date for this month, start with the first day of next month.  Subtract the appropriate number of days depending on what (numerical) day of the week the first day of the month falls on.  There\'s your "last Friday." I\'m pretty sure it can be boiled down to a longish one-liner, but I\'m not a java dev.  So I\'ll leave that to someone else. </p>\n'}, {'answer_id': 76447, 'author': 'Benno Richters', 'author_id': 3565, 'author_profile': 'https://Stackoverflow.com/users/3565', 'pm_score': 1, 'selected': False, 'text': '<p>Though I agree with scubabbl, here is a version without an inner while.</p>\n\n<pre><code>int year = 2008;\nfor (int m = Calendar.JANUARY; m &lt;= Calendar.DECEMBER; m++) {\n    Calendar cal = new GregorianCalendar(year, m, 1);\n    cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));\n    int diff = Calendar.FRIDAY - cal.get(Calendar.DAY_OF_WEEK);\n    if (diff &gt; 0) {\n        diff -= 7;\n    }\n    cal.add(Calendar.DAY_OF_MONTH, diff);\n    System.out.println(cal.getTime());\n}\n</code></pre>\n'}, {'answer_id': 76744, 'author': 'Adam Davis', 'author_id': 2915, 'author_profile': 'https://Stackoverflow.com/users/2915', 'pm_score': 2, 'selected': False, 'text': '<p>You need to know two things - the number of days in the month, and the weekday the first of the month falls on.</p>\n\n<p>If the first day of the month is a</p>\n\n<ul>\n<li>Sunday, then the last Friday is <em>always</em> the 27th.</li>\n<li>Monday, then the last Friday is <em>always</em> the 26th.</li>\n<li>Tuesday, then the last Friday is <em>always</em> the 25th.</li>\n<li>Wednesday, then the last Friday is the 24th, unless there are 31 days in the month, then it\'s the 31st</li>\n<li>Thursday, then the last Friday is the 23rd, unless there are 30 days or more in the month, then it\'s the 30th.</li>\n<li>Friday, then the last Friday is the 22nd, unless there are 29 days or more in the month, then it\'s the 29th.</li>\n<li>Saturday, then the last Friday is <em>always</em> the 28th.</li>\n</ul>\n\n<p>There are only three special cases.  A single switch statement and three if statements (or ternary operators if you like every case to have a single line...)</p>\n\n<p>Work it out on paper.  Don\'t need any special libraries, functions, julian conversions, etc (well, except to get the weekday the 1st falls on, and maybe the number of days that month... )</p>\n\n<p><a href="https://stackoverflow.com/questions/76223/get-last-friday-of-month-in-java#77315">Aaron implemented it in Java.</a></p>\n\n<p>-Adam</p>\n'}, {'answer_id': 77077, 'author': 'ColinD', 'author_id': 13792, 'author_profile': 'https://Stackoverflow.com/users/13792', 'pm_score': 6, 'selected': True, 'text': '<p>Based on <a href="https://stackoverflow.com/questions/76223/get-last-friday-of-month-in-java#76437">marked23\'s</a> suggestion:</p>\n\n<pre><code>public Date getLastFriday( int month, int year ) {\n   Calendar cal = Calendar.getInstance();\n   cal.set( year, month + 1, 1 );\n   cal.add( Calendar.DAY_OF_MONTH, -( cal.get( Calendar.DAY_OF_WEEK ) % 7 + 1 ) );\n   return cal.getTime();\n}\n</code></pre>\n'}, {'answer_id': 77315, 'author': 'Aaron', 'author_id': 7659, 'author_profile': 'https://Stackoverflow.com/users/7659', 'pm_score': 2, 'selected': False, 'text': '<p>code for <a href="https://stackoverflow.com/questions/76223/get-last-friday-of-month-in-java#76744">Adam Davis\'s algorithm</a></p>\n\n<pre><code>public static int getLastFriday(int month, int year)\n{\nCalendar cal = Calendar.getInstance();\ncal.set(year, month, 1, 0, 0, 0); // set to first day of the month\ncal.set(Calendar.MILLISECOND, 0);\n\nint firstDay = cal.get(Calendar.DAY_OF_WEEK);\nint daysOfMonth = cal.getMaximum(Calendar.DAY_OF_MONTH);\n\nswitch (firstDay)\n{\n    case Calendar.SUNDAY :\n        return 27;\n    case Calendar.MONDAY :\n        return 26;\n    case Calendar.TUESDAY :\n        return 25;\n    case Calendar.WEDNESDAY :\n        if (daysOfMonth == 31) return 31;\n        return 24;\n    case Calendar.THURSDAY :\n        if (daysOfMonth &gt;= 30) return 30;\n        return 23;\n    case Calendar.FRIDAY :\n        if (daysOfMonth &gt;= 29) return 29;\n        return 22;\n    case Calendar.SATURDAY :\n        return 28;\n}\nthrow new RuntimeException("what day of the month?");\n}}\n</code></pre>\n'}, {'answer_id': 1067710, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Hope this helps..</p>\n\n<pre><code>public static void getSundaysInThisMonth(int monthNumber, int yearNumber){\n    //int year =2009;\n    //int dayOfWeek = Calendar.SUNDAY;\n    // instantiate Calender and set to first Sunday of 2009\n    Calendar cal = new GregorianCalendar();\n    cal.set(Calendar.MONTH, monthNumber-1);\n    cal.set(Calendar.YEAR, yearNumber);\n    cal.set(Calendar.DATE, 1);\n    int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);\n    int dateOfWeek = cal.get(Calendar.DATE);\n    while (dayOfWeek  != Calendar.SUNDAY) {\n       cal.set(Calendar.DATE, ++dateOfWeek);\n       dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);\n      }\n    cal.set(Calendar.DATE, dateOfWeek);\n\n    int i = 1;\n    while (cal.get(Calendar.YEAR) == yearNumber &amp;&amp; cal.get(Calendar.MONTH)==monthNumber-1)\n    {\n            System.out.println("Sunday " + " " + i + ": " + cal.get(Calendar.DAY_OF_MONTH));\n            cal.add(Calendar.DAY_OF_MONTH, 7);\n            i++;\n    }\n\n  }\n  public static void main(String args[]){\n    getSundaysInThisMonth(1,2009);\n  }\n</code></pre>\n'}, {'answer_id': 2545695, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': '<p>Let Calendar.class do its magic for you ;)</p>\n\n<pre><code>pCal.set(GregorianCalendar.DAY_OF_WEEK,Calendar.FRIDAY);\npCal.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, -1);\n</code></pre>\n'}, {'answer_id': 7806120, 'author': 'josephus', 'author_id': 611228, 'author_profile': 'https://Stackoverflow.com/users/611228', 'pm_score': 2, 'selected': False, 'text': "<p>here's how to get the last friday, or whatever week day, of the month:</p>\n\n<pre><code>Calendar thisMonth = Calendar.getInstance();\ndayOfWeek = Calendar.FRIDAY; // or whatever\nthisMonth.set(Calendar.WEEK_OF_MONTH, thisMonth.getActualMaximum(Calendar.WEEK_OF_MONTH);;\nthisMonth.set(Calendar.DAY_OF_WEEK, dayOfWeek);\nint lastDay = thisMonth.get(Calendar.DAY_OF_MONTH); // this should be it.\n</code></pre>\n"}, {'answer_id': 9469295, 'author': 'Alexeyy Alexeyy', 'author_id': 1192726, 'author_profile': 'https://Stackoverflow.com/users/1192726', 'pm_score': -1, 'selected': False, 'text': '<pre><code>public static Calendar getNthDow(int month, int year, int dayOfWeek, int n) {\n    Calendar cal = Calendar.getInstance();\n    cal.set(year, month, 1);\n    cal.set(Calendar.DAY_OF_WEEK, dayOfWeek);\n    cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, n);\n    return (cal.get(Calendar.MONTH) == month) &amp;&amp; (cal.get(Calendar.YEAR) == year) ? cal : null;\n}\n</code></pre>\n'}, {'answer_id': 10922864, 'author': 'akshay jangid', 'author_id': 1440879, 'author_profile': 'https://Stackoverflow.com/users/1440879', 'pm_score': 1, 'selected': False, 'text': '<p>Below program is for the last Friday of each month. it can be used to get the last of any day of the week in any month. The variable <code>offset=0</code> means current month(system date), offset=1 means next month, so on. The <code>getLastFridayofMonth(int offset)</code> method will return the last Friday.</p>\n\n<pre><code>import java.text.SimpleDateFormat;\nimport java.util.Calendar;\n\npublic class LastFriday {\n\n  public static Calendar getLastFriday(Calendar cal,int offset){\n    int dayofweek;//1-Sunday,2-Monday so on....\n    cal.set(Calendar.MONTH,cal.get(Calendar.MONTH)+offset);\n    cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); //set calendar to last day of month\n    dayofweek=cal.get(Calendar.DAY_OF_WEEK); //get the day of the week for last day of month set above,1-sunday,2-monday etc\n    if(dayofweek&lt;Calendar.FRIDAY)  //Calendar.FRIDAY will return integer value =5 \n      cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)-7+Calendar.FRIDAY-dayofweek);\n    else\n      cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)+Calendar.FRIDAY-dayofweek); \n\n    return cal;\n  }\n\n  public static String  getLastFridayofMonth(int offset) { //offset=0 mean current month\n    final String DATE_FORMAT_NOW = "dd-MMM-yyyy";\n    Calendar cal = Calendar.getInstance();\n    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);\n    cal=getLastFriday(cal,offset);\n    return sdf.format(cal.getTime()); \n\n  }\n\n  public static void main(String[] args) {\n    System.out.println(getLastFridayofMonth(0)); //0 = current month\n    System.out.println(getLastFridayofMonth(1));//1=next month\n    System.out.println(getLastFridayofMonth(2));//2=month after next month\n  }\n\n}\n</code></pre>\n'}, {'answer_id': 22397346, 'author': 'Dhananjay Chauhan', 'author_id': 3418626, 'author_profile': 'https://Stackoverflow.com/users/3418626', 'pm_score': 0, 'selected': False, 'text': '<pre><code>public static int lastSundayDate()\n{\n    Calendar cal = getCalendarInstance();\n    cal.setTime(new Date(getUTCTimeMillis()));\n    cal.set( Calendar.DAY_OF_MONTH , 25 );\n    return (25 + 8 - (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY ? cal.get(Calendar.DAY_OF_WEEK) : 8));\n}\n</code></pre>\n'}, {'answer_id': 33867973, 'author': 'Przemek', 'author_id': 1981559, 'author_profile': 'https://Stackoverflow.com/users/1981559', 'pm_score': 4, 'selected': False, 'text': '<h1>java.time</h1>\n\n<p>Using <a href="http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html" rel="noreferrer">java.time</a> library built into Java 8 and later, you may use <a href="https://docs.oracle.com/javase/8/docs/api/java/time/temporal/TemporalAdjusters.html#lastInMonth-java.time.DayOfWeek-" rel="noreferrer"><code>TemporalAdjusters.lastInMonth</code></a>:</p>\n\n<pre><code>val now = LocalDate.now() \nval lastInMonth = now.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY))\n</code></pre>\n\n<p>You may choose any day from the <a href="http://docs.oracle.com/javase/8/docs/api/java/time/DayOfWeek.html" rel="noreferrer"><code>DayOfWeek</code></a> enum.</p>\n\n<p>If you need to add time information, you may use any available <a href="http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html" rel="noreferrer"><code>LocalDate</code></a> to <a href="http://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html" rel="noreferrer"><code>LocalDateTime</code></a> conversion like</p>\n\n<pre><code>lastFriday.atStartOfDay() // e.g. 2015-11-27T00:00\n</code></pre>\n'}, {'answer_id': 40993952, 'author': 'KayV', 'author_id': 3956731, 'author_profile': 'https://Stackoverflow.com/users/3956731', 'pm_score': 1, 'selected': False, 'text': '<p>In Java 8, we can do it simply as:</p>\n\n<pre><code>LocalDate lastFridayOfMonth = LocalDate\n                                    .now()\n                                    .with(lastDayOfMonth())\n                                    .with(previous(DayOfWeek.FRIDAY));\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/76223', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7008/']