13

I am trying to get the first date and the last date of the given month and year. I used the following code to get the last date in the format yyyyMMdd. But couldnot get this format. Also then I want the start date in the same format. I am still working on this. Can anyone help me in fixing the below code.

public static java.util.Date calculateMonthEndDate(int month, int year) {
    int[] daysInAMonth = { 29, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    int day = daysInAMonth[month];
    boolean isLeapYear = new GregorianCalendar().isLeapYear(year);

    if (isLeapYear && month == 2) {
        day++;
    }
    GregorianCalendar gc = new GregorianCalendar(year, month - 1, day);
    java.util.Date monthEndDate = new java.util.Date(gc.getTime().getTime());
    return monthEndDate;
}

public static void main(String[] args) {
    int month = 3;
    int year = 2076;
    final java.util.Date calculatedDate = calculateMonthEndDate(month, year);
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
    format.format(calculatedDate);
    System.out.println("Calculated month end date : " + calculatedDate);
} 
user1514499
  • 762
  • 7
  • 26
  • 63
  • 4
    Well what results *are* you getting? And why are you converting from a `Date` (the result of `Calendar.getTime()` to a `long`, and then creating a new `Date`)? And could you switch to using Joda Time, which would make all of this much neater? – Jon Skeet Jan 23 '13 at 08:44

9 Answers9

23

java.time.YearMonth methods atDay & atEndOfMonth

The java.time framework built into Java 8+ (Tutorial) has commands for this.

The aptly-named YearMonth class represents a month of a year, without any specific day or time. From there we can ask for the first and days of the month.

YearMonth yearMonth = YearMonth.of( 2015, 1 );     // 2015-01. January of 2015.
LocalDate firstOfMonth = yearMonth.atDay( 1 );     // 2015-01-01
LocalDate lastOfMonth = yearMonth.atEndOfMonth();  // 2015-01-31

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
8

Simply you can use Calendar class. you should assign month variable which month you want

        Calendar gc = new GregorianCalendar();
        gc.set(Calendar.MONTH, month);
        gc.set(Calendar.DAY_OF_MONTH, 1);
        Date monthStart = gc.getTime();
        gc.add(Calendar.MONTH, 1);
        gc.add(Calendar.DAY_OF_MONTH, -1);
        Date monthEnd = gc.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

        System.out.println("Calculated month start date : " + format.format(monthStart));
        System.out.println("Calculated month end date : " + format.format(monthEnd));
engtuncay
  • 867
  • 10
  • 29
7

First day:

Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH);

Last day of month:

Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);
Vladimir Vagaytsev
  • 2,871
  • 9
  • 33
  • 36
5
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
format.format(calculatedDate);
System.out.println("Calculated month end date : " + calculatedDate);

Change it to

SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
String formattedDate =  format.format(calculatedDate);
System.out.println("Calculated month end date : " + formattedDate);

For more detail

http://docs.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html#format(java.util.Date)

Another Approach

package com.shashi.mpoole;

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

public class DateMagic {

     public static String PATTERN = "yyyyMMdd";

     static class Measure {
           private int month;
           private int year;
           private Calendar calendar;

           public Measure build() {

                calendar = Calendar.getInstance();
                calendar.set(year, month, 1);

                return this;
           }

           public Measure(int year, int month) {
                this.year(year);
                this.month(month);
           }

           public String min() {
                  return format(calendar.getActualMinimum(Calendar.DATE));
           }

           public String max() {
                  return format(calendar.getActualMaximum(Calendar.DATE));
           }

           private Date date(GregorianCalendar c) {
                  return new java.util.Date(c.getTime().getTime());

           }

           private GregorianCalendar gc(int day) {
                  return new GregorianCalendar(year, month, day);
           }

           private String format(int day) {

                  SimpleDateFormat format = new SimpleDateFormat(PATTERN);
                  return format.format(date(gc(day)));
           }

           public void month(int month) {
                  this.month = month - 1;
           }

           public void year(int year) {
                  this.year = year;
           }
      }

      public static void main(String[] args) {

             Measure measure = new Measure(2020, 6).build();

             System.out.println(measure.min());
             System.out.println(measure.max());

        
    }

}
Shashi
  • 12,487
  • 17
  • 65
  • 111
5

To get the Start Date

    GregorianCalendar gc = new GregorianCalendar(year, month-1, 1);
    java.util.Date monthEndDate = new java.util.Date(gc.getTime().getTime());
    System.out.println(monthEndDate);

(Note : in the Start date the day =1)

for the formatted

SimpleDateFormat format = new SimpleDateFormat(/////////add your format here);
System.out.println("Calculated month end date : " + format.format(calculatedDate));
Alya'a Gamal
  • 5,624
  • 19
  • 34
  • FYI, the terribly troublesome date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), `GregorianCalendar`, and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jun 07 '19 at 05:45
4

Try below code for last day of month : -

Calendar c = Calendar.getInstance();      
c.set(2012,3,1); //------>  
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));  

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");  
System.out.println(sdf.format(c.getTime())); 

http://www.coderanch.com/t/385759/java/java/date-date-month

duggu
  • 37,851
  • 12
  • 116
  • 113
2

Although, not exactly the answer for the OP question, below methods will given current month first & last dates as Java 8+ LocalDate instances.

public static LocalDate getCurrentMonthFirstDate() {
    return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).withDayOfMonth(1);
}

public static LocalDate getCurrentMonthLastDate() {
    return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).plusMonths(1).withDayOfMonth(1).minusDays(1);
}

Side note: Using LocalDate.ofEpochDay(...) instead of LocalDate.now() gives much improved performance. Also, using the millis-in-a-day expression instead of the end value, which is 86400000 is performing better. I initially thought the latter would perform better than the the expression :P

Why this answer: Even this is not a correct answer for OP question, I m still answering here as Google showed this question when I searched for 'java 8 get month start date' :)

manikanta
  • 8,100
  • 5
  • 59
  • 66
1
        GregorianCalendar gc = new GregorianCalendar(year, selectedMonth-1, 1);
           java.util.Date monthStartDate = new java.util.Date(gc.getTime().getTime());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(monthStartDate);
        calendar.add(calendar.MONTH, 1);
        calendar.add(calendar.DAY_OF_MONTH, -1);
           java.util.Date monthEndDate = new java.util.Date(calendar.getTime())
  • 2
    Your answer should contains an explanation of your code and a description how it solves the problem. – AbcAeffchen Sep 01 '14 at 06:45
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque May 07 '18 at 20:36
1
public static Date[] getMonthInterval(Date data) throws Exception {

    Date[] dates = new Date[2];

    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();

    start.setTime(data);
    start.set(Calendar.DAY_OF_MONTH, start.getActualMinimum(Calendar.DAY_OF_MONTH));
    start.set(Calendar.HOUR_OF_DAY, 0);
    start.set(Calendar.MINUTE, 0);
    start.set(Calendar.SECOND, 0);

    end.setTime(data);
    end.set(Calendar.DAY_OF_MONTH, end.getActualMaximum(Calendar.DAY_OF_MONTH));
    end.set(Calendar.HOUR_OF_DAY, 23);
    end.set(Calendar.MINUTE, 59);
    end.set(Calendar.SECOND, 59);

    //System.out.println("start "+ start.getTime());
    //System.out.println("end   "+ end.getTime());

    dates[0] = start.getTime();
    dates[1] = end.getTime();

    return dates;
}
  • FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque May 07 '18 at 20:36