How to get the first date and last date of the previous month? (Java)

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.

Upvotes: 22

Views: 41326

Answers (9)

Basil Bourque
Basil Bourque

Reputation: 340230

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.

Upvotes: 10

kiran..
kiran..

Reputation: 19

//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);

Upvotes: 2

SHRIDHAR K
SHRIDHAR K

Reputation: 40

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.

Upvotes: 2

vyshnavi
vyshnavi

Reputation: 11

    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;
    }
}

Upvotes: 1

GoYun.Info
GoYun.Info

Reputation: 1366

    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();

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240996

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

Upvotes: 36

Surender Thakran
Surender Thakran

Reputation: 4054

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

Upvotes: 2

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299218

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.

Upvotes: 4

tagtraeumer
tagtraeumer

Reputation: 1491

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.

Upvotes: 3

Related Questions