20

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.

jmj
  • 237,923
  • 42
  • 401
  • 438

9 Answers9

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

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 1
    Do we ever need to use `getActualMinimum`? Or just assume it to always be 1? – ADTC Apr 11 '16 at 03:53
  • 1
    for Date you can assume it to be 1 for Gregorian calendar, but there are multiple other fields as well, [check this out](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/GregorianCalendar.java#GregorianCalendar.0MIN_VALUES – jmj Apr 11 '16 at 06:32
  • 2
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html), and `java.text.SimpleTextFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Sep 09 '17 at 21:55
9

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • See my [similar answer](http://stackoverflow.com/a/26321291/642706) to duplicate question for more discussion of this kind of code. – Basil Bourque Oct 13 '14 at 08: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. – Ole V.V. Mar 05 '19 at 08:22
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.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • The midnight classes and methods on Joda-Time have been deprecated. Use the method `withTimeAtStartOfDay`. – Basil Bourque Sep 01 '14 at 07:43
  • 1
    FYI, the [Joda-Time](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), with the team advising migration to the [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Sep 09 '17 at 21:54
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.

tagtraeumer
  • 1,451
  • 11
  • 19
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
Surender Thakran
  • 3,958
  • 11
  • 47
  • 81
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.

SHRIDHAR K
  • 40
  • 1
  • 4
  • 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?](https://stackoverflow.com/help/how-to-answer). Thanks – sɐunıɔןɐqɐp Dec 14 '19 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](https://stackoverflow.com/posts/59335432/edit) link under the question.) – Ole V.V. Dec 14 '19 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);
kiran..
  • 19
  • 4
  • 1
    I have tried multiple ways at last this fulfilled my requirement, for more date generators visit https://github.com/kreddy27/https---github.com-kreddy27-mythoughts – kiran.. Feb 13 '20 at 04:52
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();
GoYun.Info
  • 1,356
  • 12
  • 12
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;
    }
}
soorapadman
  • 4,451
  • 7
  • 35
  • 47
vyshnavi
  • 11
  • 1