21

With today's date, I should get the first date and last date of the previous month. I am unable to come up with any logic.

For example, on passing 05/30/2012, I should get 04/01/2012 and 04/30/2012.

Any help will be much appreciated. Thanks.

9 Answers 9

36

With Calendar

Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DATE, 1);
Date firstDateOfPreviousMonth = cal.getTime();

cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE)); // changed calendar to cal

Date lastDateOfPreviousMonth = cal.getTime();

See

3
10

tl;dr

YearMonth.now().minusMonths( 1 ).atDay( 1 )

…and…

YearMonth.now().minusMonths( 1 ).atEndOfMonth()

Avoid j.u.Date

Avoid the bundled java.util.Date and .Calendar classes as they are notoriously troublesome. Instead, use the java.time package in Java 8 and later.

java.time

The new java.time framework in 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 last days of the month.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
YearMonth yearMonthNow = YearMonth.now( zoneId );
YearMonth yearMonthPrevious = yearMonthNow.minusMonths( 1 );
LocalDate firstOfMonth = yearMonthPrevious.atDay( 1 );
LocalDate lastOfMonth = yearMonthPrevious.atEndOfMonth();

Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.

In Joda-Time 2.8, use the LocalDate class if you do not care about time-of-day.

LocalDate today = LocalDate.now( DateTimeZone.forID( "Europe/Paris" ) );
LocalDate firstOfThisMonth = today.withDayOfMonth( 1 );
LocalDate firstOfLastMonth = firstOfThisMonth.minusMonths( 1 );
LocalDate endOfLastMonth = firstOfThisMonth.minusDays( 1 );

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.

5
  • See my similar answer to duplicate question for more discussion of this kind of code. Commented Oct 13, 2014 at 8:25
  • This is the recommended answer in 2019. I further recommend passing explicit time zone or offset to now, for example YearMonth.now(ZoneOffset.UTC) so it’s clear to the reader (and yourself) what you get.
    – Anonymous
    Commented Mar 5, 2019 at 8:22
  • Thanks for the info. And in case someone also meets the scenario, needs the format to be like "2023_07"(the default value will be "2023-07"), we can run the following: println(YearMonth.now().minusMonths(2).format(DateTimeFormatter.ofPattern("yyyy_MM")).inspect())
    – MadHatter
    Commented Sep 12, 2023 at 3:24
  • 1
    @MadHatter Or .replace( "-" , "_" ) Commented Sep 12, 2023 at 4:05
  • @BasilBourque Of course, that will do, thanks for the update.
    – MadHatter
    Commented Sep 12, 2023 at 4:59
4

Use JodaTime

DateMidnight now = new DateMidnight();
DateMidnight beginningOfLastMonth = now.minusMonths(1).withDayOfMonth(1);
DateMidnight endOfLastMonth = now.withDayOfMonth(1).minusDays(1);
System.out.println(beginningOfLastMonth);
System.out.println(endOfLastMonth);

Output:

2012-04-01T00:00:00.000+02:00
2012-04-30T00:00:00.000+02:00

Explanation: a DateMidnight object is a Date Object with no time of day information, which seems like just what you need. If not, replace all occurrences of DateMidnight with DateTime in the above code.

2
3

well you could create a calendar object, set the date to the first day of the current month (should be the first :P) and then you can do two operations: from your calendar object you can subtract a particular period of time, e.g. a month (this would give you the first date of the previous month, or a day, which would give you the last day of the previous month. i didn't try it but this would be my first steps.

2

Would also like to add something to Jigar's answer. Use the DateFormat class to get the date in the format you specified in the question:

DateFormat df = DateFormat.getInstance(DateFormat.SHORT);
System.out.println(df.format(firstDateOfPreviousMonth));
System.out.println(df.format(lastDateOfPreviousMonth));

Output:

04/01/12
04/30/12
0
2
public static LocalDate getPreviousMonthStartDate() {

    return LocalDate.now().minusMonths(1).with(TemporalAdjusters.firstDayOfMonth());
}

public static LocalDate getPreviousMonthLastDate() {

    return LocalDate.now().minusMonths(1).with(TemporalAdjusters.lastDayOfMonth());
}

Using Java.Time is very easy to write code. java.time package has better design, more thread safe , lot of utility methods to support common operations and easy to handle timezone with Local and ZonedDate/Time APIs.

2
  • 3
    From Review: Hi, please don't answer just with source code. Try to provide a nice description about how your solution works. See: How do I write a good answer?. Thanks Commented Dec 14, 2019 at 13:31
  • 2
    Upvoted because the code i good. Using java.time is a good idea. I very much agree with the review comment: It’s from the explanations that we all learn, so if you could provide some of that too? (You’ve got an edit link under the question.)
    – Anonymous
    Commented Dec 14, 2019 at 16:01
2

//in the pattern you can use your desired format.

  DateTimeFormatter format = DateTimeFormatter.ofPattern("MM/dd/yyyy");
                LocalDate now = LocalDate.now();
                String startDate = now.minusMonths(1).with(TemporalAdjusters.firstDayOfMonth()).format(format);
                String endDate = now.minusMonths(1).with(TemporalAdjusters.lastDayOfMonth()).format(format);
1
1
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.DATE, 1);
    cal.add(Calendar.DAY_OF_MONTH, -1);
    Date lastDateOfPreviousMonth = cal.getTime();
    cal.set(Calendar.DATE, 1);
    Date firstDateOfPreviousMonth = cal.getTime();
1
    public List customizeDate(String month, int year) {
        List<String> list = new ArrayList<String>();
        try {
            String edates = null;
            String sdates = null;
            if (month.equals("JAN") || month.equals("MAR") ||
                month.equals("MAY") || month.equals("JUL") ||
                month.equals("AUG") || month.equals("OCT") ||
                month.equals("DEC")) {
                String s1 = "01";
                String s2 = "31";

                String sdate = s1 + "-" + month + "-" + year;
                System.out.println("Startdate" + sdate);
                SimpleDateFormat sd = new SimpleDateFormat("dd-MMM-yyyy");
                Date ed = sd.parse(sdate);
                sdates = sd.format(ed);
                System.out.println("ed" + ed + "------------" + sdates);
                String endDate = s2 + "-" + month + "-" + year;
                System.out.println("EndDate" + endDate);
                SimpleDateFormat s = new SimpleDateFormat("dd-MMM-yyyy");
                Date d = s.parse(endDate);
                edates = s.format(d);
                System.out.println("d" + d + "------------" + edates);
            } else if (month.equals("APR") || month.equals("JUN") ||
                       month.equals("SEP") || month.equals("NOV")) {
                String s3 = "01";
                String s4 = "30";
                String sdate = s3 + "-" + month + "-" + year;
                System.out.println("Startdate" + sdate);
                SimpleDateFormat sd = new SimpleDateFormat("dd-MMM-yyyy");
                Date ed = sd.parse(sdate);
                sdates = sd.format(ed);
                System.out.println("ed" + ed + "------------" + sdates);
                String endDate = s4 + "-" + month + "-" + year;
                System.out.println("EndDate" + endDate);
                SimpleDateFormat s = new SimpleDateFormat("dd-MMM-yyyy");
                Date d = s.parse(endDate);
                edates = s.format(d);
                System.out.println("d" + d + "------------" + edates);
            } else {
                if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
                    System.out.println("Leap year");
                    if (month.equals("FEB")) {
                        String s5 = "01";
                        String s6 = "29";
                        String sdate = s5 + "-" + month + "-" + year;
                        System.out.println("Startdate" + sdate);
                        SimpleDateFormat sd =
                            new SimpleDateFormat("dd-MMM-yyyy");
                        Date ed = sd.parse(sdate);
                        sdates = sd.format(ed);
                        System.out.println("ed" + ed + "------------" +
                                           sdates);
                        String endDate = s6 + "-" + month + "-" + year;
                        System.out.println("EndDate" + endDate);
                        SimpleDateFormat s =
                            new SimpleDateFormat("dd-MMM-yyyy");
                        Date d = s.parse(endDate);
                        edates = s.format(d);
                        System.out.println("d" + d + "------------" + edates);
                    }
                } else {
                    System.out.println("Not a leap year");
                    String s7 = "01";
                    String s8 = "28";
                    String sdate = s7 + "-" + month + "-" + year;
                    System.out.println("Startdate" + sdate);
                    SimpleDateFormat sd = new SimpleDateFormat("dd-MMM-yyyy");
                    Date ed = sd.parse(sdate);
                    sdates = sd.format(ed);
                    System.out.println("ed" + ed + "------------" + sdates);
                    String endDate = s8 + "-" + month + "-" + year;
                    System.out.println("EndDate" + endDate);
                    SimpleDateFormat s = new SimpleDateFormat("dd-MMM-yyyy");
                    Date d = s.parse(endDate);
                    edates = s.format(d);
                    System.out.println("d" + d + "------------" + edates);
                }
            }
            list.add(edates);
            list.add(sdates);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        return list;
    }
}
1
  • 3
    Write some details to the answer rather posting only code . Commented Jan 7, 2019 at 6:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.