Get The First Day Of The Month From Date Object
In this example we show you how you can get the first day of the month. Most of the time we use a java.util.Date
Object to represent a Date. We can use the java.util.Calendar
class to manipulate the date object. First we create a Calendar Object and set it’s time with a Date Object. Next we can set the Day of the Month to the ‘actual minimum’. You can also just set this value to 1 because every month will start with 1. Finally we return a new Date Object representing the First day of the Month.
First Day Of The Month
package com.memorynotfound.date;
import java.util.Calendar;
import java.util.Date;
public class GetFirstDayOfMonth {
public static void main(String... args){
System.out.println("First day of the month: " + getFirstDateOfMonth(new Date()));
}
public static Date getFirstDateOfMonth(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
return cal.getTime();
}
}
Demo
First day of month: Thu Jan 01 14:19:47 CET 2015