4

I have an issue with getting correct date of last Monday of previous month. I think there isn't absolutely right to calculate it like in this question and want to refuse arithmetic operations with constants. This code working as expected:

public class mCalendar {
  private int thisMonth;
  private int prevMonth;
  private int lstDayThisMonth;
  private int lstDayPrevMonth;
  private int weekOffset;
  private int LstMnd;
  public String monthLetter;
  Locale locale = Locale.getDefault();
  private Calendar mCal;

public mCalendar(){
  this.mCal = Calendar.getInstance();
  mCal.set(Calendar.MONTH,0);
  this.thisMonth = mCal.get(Calendar.MONTH);
  this.prevMonth = thisMonth - 1;
  this.lstDayThisMonth = mCal.getActualMaximum(Calendar.DAY_OF_MONTH);
  this.monthLetter = mCal.getDisplayName(Calendar.MONTH, Calendar.LONG, locale);

  mCal.set(Calendar.MONTH,prevMonth);
  this.lstDayPrevMonth = mCal.getActualMaximum(Calendar.DAY_OF_MONTH);
  mCal.set(Calendar.DAY_OF_MONTH,lstDayPrevMonth);
  this.LstMnd = mCal.get(Calendar.DAY_OF_WEEK_IN_MONTH);
  mCal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
  mCal.set(Calendar.DAY_OF_WEEK_IN_MONTH, LstMnd);
  this.weekOffset = mCal.get(Calendar.DAY_OF_MONTH);
}

But when I set Calendar.MONTH to 1 in second instruction of constructor's body Calendar.DAY_OF_MONTH return frist Monday of February. I expect the function return me January 26 but it's return February 2. I think it's happens because February 1 it's a Sunday but, for example, for March code is working correct.

Help me please, i'm confused)

Community
  • 1
  • 1
Alex_H
  • 134
  • 11

2 Answers2

2

Why not use a library like Joda:

LocalDate lastDay = new LocalDate().minusMonths(1).dayOfMonth().withMaximumValue();
LocalDate lastMonday = lastDayOfMonth.dayOfWeek().withMinimumValue();
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • Note that the question asks for "last *Monday* of the previous month", not last *day* of the previous month. I'd start my approach like this, however. – Andy Turner May 27 '15 at 19:15
  • Thank's for your reply but I don't sure it's right to use whole external library for this simple purpose. Why the code work correctly for other month except February? Just can't undesrtand what am I doing wrong. – Alex_H May 28 '15 at 08:36
  • 1
    I don't understand why in 2015 people are still reluctant to add a small library to their projects to make their life easier: +10kB on the final package is not gonna make any difference... – Jean Logeart May 28 '15 at 13:52
  • 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/9/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jan 29 '18 at 03:59
1

tl;dr

date of last Monday of previous month

YearMonth.from(                                                // Represent entire month as a whole.
    LocalDate.now( ZoneId.of( "Africa/Tunis" ) )               // Determine today’s date for a particular time zone.
)
.minusMonths( 1 )                                              // Move to prior `YearMonth`.
.atEndOfMonth()                                                // Get the last day of that prior month as a `LocalDate`.
.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) )  // Move to another date for a Monday, or remain if already on a Monday.

java.time

The modern approach uses the java.time classes rather than the troublesome old Calendar class.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.

Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.

LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;

Get the the month as a whole with YearMonth class.

YearMonth thisMonth = YearMonth.from( ld ) ;

Move to prior month.

YearMonth priorMonth = thisMonth.minusMonths( 1 ) ;

Get the last day of that previous month.

LocalDate endOfPriorMonth = priorMonth.atEndOfMonth() ;

Get the prior Monday relative to the end of that previous month, unless the end of the month is itself a Monday. Do this with a TemporalAdjuster implementation found in TemporalAdjusters class.

LocalDate lastMondayOfPriorMonth = endOfPriorMonth.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) ) ;

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.

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