32

How would I go about getting the first day of the month? So for January, of this year, it would return Sunday. And then for February it would return Wednesday.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Austin Donovan
  • 321
  • 1
  • 3
  • 3

9 Answers9

45

To get the first date of the current month, use java.util.Calendar. First get an instance of it and set the field Calendar.DAY_OF_MONTH to the first date of the month. Since the first day of any month is 1, inplace of cal.getActualMinimum(Calendar.DAY_OF_MONTH), 1 can be used here.

private Date getFirstDateOfCurrentMonth() {
  Calendar cal = Calendar.getInstance();
  cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
  return cal.getTime();
}
lol
  • 5
  • 2
Nadeeshani
  • 493
  • 4
  • 8
  • 1
    Note that you'll want `cal.getActualMinimum` instead if the calendar object has been set to a specific month in the past. – danhbear Mar 17 '15 at 23:49
16

You can create a Calendar with whatever date you want and then do set(Calendar.DAY_OF_MONTH, 1) to get the first day of a month.

     Calendar cal = Calendar.getInstance();
     cal.set(Calendar.DATE, 25);
     cal.set(Calendar.MONTH, Calendar.JANUARY);
     cal.set(Calendar.YEAR, 2012);

     cal.set(Calendar.DAY_OF_MONTH, 1);
     Date firstDayOfMonth = cal.getTime();  

     DateFormat sdf = new SimpleDateFormat("EEEEEEEE");   
     System.out.println("First Day of Month: " + sdf.format(firstDayOfMonth));  
heenenee
  • 19,914
  • 1
  • 60
  • 86
Kushan
  • 10,657
  • 4
  • 37
  • 41
7
public int getFirstDay(){
    Calendar c=new GregorianCalendar();
    c.set(Calendar.DAY_OF_MONTH, 1);
    return c.get(Calendar.DAY_OF_WEEK);
}

From there you can see if the int is equal to Calendar.SUNDAY, Calendar.MONDAY, etc.

Joe
  • 7,922
  • 18
  • 54
  • 83
3

In the Java 8 you can use the TemporalAdjusters:

This is an example:

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;

/**
 * Dates in Java8
 *
 */
public class App {
    public static void main(String[] args) {
        LocalDate localDate = LocalDate.now();
        System.out.println("Day of Month: " + localDate.getDayOfMonth());
        System.out.println("Month: " + localDate.getMonth());
        System.out.println("Year: " + localDate.getYear());

        System.out.printf("first day of Month: %s%n",
                localDate.with(TemporalAdjusters.firstDayOfMonth()));
        System.out.printf("first Monday of Month: %s%n", localDate
                .with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)));
        System.out.printf("last day of Month: %s%n",
                localDate.with(TemporalAdjusters.lastDayOfMonth()));
        System.out.printf("first day of next Month: %s%n",
                localDate.with(TemporalAdjusters.firstDayOfNextMonth()));
        System.out.printf("first day of next Year: %s%n",
                localDate.with(TemporalAdjusters.firstDayOfNextYear()));
        System.out.printf("first day of Year: %s%n",
                localDate.with(TemporalAdjusters.firstDayOfYear()));

        LocalDate tomorrow = localDate.plusDays(1);
        System.out.println("Day of Month: " + tomorrow.getDayOfMonth());
        System.out.println("Month: " + tomorrow.getMonth());
        System.out.println("Year: " + tomorrow.getYear());
    }

}

The results would be:

Day of Month: 16
Month: MAY
Year: 2014
first day of Month: 2014-05-01
first Monday of Month: 2014-05-05
last day of Month: 2014-05-31
first day of next Month: 2014-06-01
first day of next Year: 2015-01-01
first day of Year: 2014-01-01
Last in Month Tuesday: 2014-05-27
Day of Month: 17
Month: MAY
Year: 2014
Gabriel
  • 2,011
  • 14
  • 14
3

TemporalAdjuster

In java 8 you can use the new LocalDate and LocalTime API.

To achieve the coveted result, give a try to the following. It prints the name of the given day.

import java.time.*;
import java.time.temporal.*;

public class Main {
  public static void main(String[] args) {
    LocalDate l = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
    System.out.println(l.getDayOfWeek());
  }
}

Explanation:

  • now gives you the current date.
  • by calling with you can pass a TemporalAdjuster which are a key tool for modifying temporal objects.
  • getDayOfWeek Gets the day-of-week field, which is an enum DayOfWeek. This includes textual names of the values.

TemporalAdjuster has a brother class, called TemporalAdjusters which contains static methods regarding the adjustments, like the one you are looking for, the firstDayOfMonth

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Mark
  • 5,994
  • 5
  • 42
  • 55
2

java.time

Since Java 8 we can also use YearMonth class which allows us to create LocalDate objects with specified days (first, last). Then We can simply convert these dates to DayOfWeek Enum (Tutorial) and read its name property.

YearMonth ym = YearMonth.of(2012, 1);

String firstDay = ym.atDay(1).getDayOfWeek().name();
String lastDay = ym.atEndOfMonth().getDayOfWeek().name();

System.out.println(firstDay);
System.out.println(lastDay);

result:

SUNDAY
TUESDAY
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Pshemo
  • 122,468
  • 25
  • 185
  • 269
2

Create java.util.Date or java.util.Calendar object, set date value and use java.text.SimpleDateFormat class method to format it.

 Calendar cal=Calendar.getInstance();
 cal.set(Calendar.DATE,1);
 cal.set(Calendar.MONTH,0);
 cal.set(Calendar.YEAR,2012);

 SimpleDateFormat sdf=new SimpleDateFormat("EEEE");
 System.out.println(sdf.format(cal.getTime()));
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
1

java.time, soft-coded

The Answer by Pshemo was good and clever, but is hard-coded to English. Let's take a stab at it allowing for localization.

ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Time zone is crucial to determining a date.
YearMonth yearMonth = YearMonth.now( zoneId );
LocalDate firstOfMonth = yearMonth.atDay( 1 );

Formatter

Generate a textual representation of that LocalDate. We specify a desired Locale, in this case CANADA_FRENCH. If omitted, your JVM’s current default Locale is implicitly applied; better to specify explicit Locale.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "EEEE" ).withZone( zoneId ).withLocale( Locale.CANADA_FRENCH );  // Exactly four 'E' letters means full form. http://docs.oracle.com/javase/8/docs/api/java/time/format/TextStyle.html#FULL
String output = formatter.format( firstOfMonth );

Dump to console.

System.out.println( "output: " + output );

When run.

samedi

DayOfWeek Enum

Another route is to use the DayOfWeek enum. This enum includes a getDisplayName method where you specify both the text style (full name versus abbreviation) and a Locale.

DayOfWeek dayOfWeek = firstOfMonth.getDayOfWeek() ;
String output = dayOfWeek.getDisplayName( TextStyle.FULL_STANDALONE  , Locale.CANADA_FRENCH ) ;
Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

Simple and tricky answer

    val calendar = Date()    
    val sdf = SimpleDateFormat("yyyy-MM-01 00:00:00", Locale.getDefault())
    var result = sdf.format(calendar)

yyyy-MM-01 -> dd change to 01

Suhad Bin Zubair
  • 717
  • 7
  • 10