Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 648
venkateshwarrao surabhi Avatar asked May 31 '12 06:05

venkateshwarrao surabhi


People also ask

How do I get previous month LocalDate?

Create an object. GregorianCalendar cal = (GregorianCalendar) GregorianCalendar. getInstance(); Now, use the following field and add() method with a negative one (-1) to display the previous month.

How do you check if a date is after another date in Java?

The after() method is used to check if a given date is after another given date. Return Value: true if and only if the instant represented by this Date object is strictly later than the instant represented by when; false otherwise.

Is last day of month Java?

Use the getActualMaximum() method to get the last day of the month. int res = cal. getActualMaximum(Calendar. DATE);


4 Answers

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

  • ideone demo
like image 59
jmj Avatar answered Oct 24 '22 02:10

jmj


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?

  • Java SE 8, Java SE 9, Java SE 10, and later
  • Built-in.
  • Part of the standard Java API with a bundled implementation.
  • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
  • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
  • Later versions of Android bundle implementations of the java.time classes.
  • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

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.

like image 10
Basil Bourque Avatar answered Oct 24 '22 01:10

Basil Bourque


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.

like image 4
Sean Patrick Floyd Avatar answered Oct 24 '22 02:10

Sean Patrick Floyd


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.

like image 3
tagtraeumer Avatar answered Oct 24 '22 02:10

tagtraeumer