Return a Date set to the first possible millisecond of the month, just after midnight in Java

Description

The following code shows how to return a Date set to the first possible millisecond of the month, just after midnight.

Example


/*from   w  w w.j  ava 2s.c  om*/
import java.util.Calendar;
import java.util.Date;

public class Main {
  public static Date getStartOfMonth(Date day) {
    return getStartOfMonth(day, Calendar.getInstance());
  }

  public static Date getStartOfMonth(Date day, Calendar cal) {
    if (day == null)
      day = new Date();
    cal.setTime(day);

    // set time to start of day
    cal.set(Calendar.HOUR_OF_DAY, cal.getMinimum(Calendar.HOUR_OF_DAY));
    cal.set(Calendar.MINUTE, cal.getMinimum(Calendar.MINUTE));
    cal.set(Calendar.SECOND, cal.getMinimum(Calendar.SECOND));
    cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND));

    // set time to first day of month
    cal.set(Calendar.DAY_OF_MONTH, 1);

    return cal.getTime();
  }

  public static void main(String[] argv) {
    System.out.println(getStartOfMonth(new Date()));
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Date »




Date Get
Date Set
Date Format
Date Compare
Date Convert
Date Calculation
Date Parse
Timezone