Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Main {

    public static Calendar getLastFriday(Calendar cal, int offset) {
        int dayofweek;
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + offset);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        dayofweek = cal.get(Calendar.DAY_OF_WEEK);
        if (dayofweek < Calendar.FRIDAY)
            cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) - 7 + Calendar.FRIDAY - dayofweek);
        else
            cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) + Calendar.FRIDAY - dayofweek);

        return cal;
    }

    public static String getLastFridayofMonth(int offset) {
        final String DATE_FORMAT_NOW = "dd-MMM-yyyy";
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
        cal = getLastFriday(cal, offset);
        return sdf.format(cal.getTime());
    }

    public static void main(String[] args) {
        System.out.println(getLastFridayofMonth(0)); // 0 = current month
        System.out.println(getLastFridayofMonth(1));// 1=next month
        System.out.println(getLastFridayofMonth(2));// 2=month after next month
        System.out.println(getLastFridayofMonth(3));
    }

}