Get first Monday after certain date?
Asked Answered
A

5

6

If my app received a certain date, how can I find out the date of first next Monday?

For example, I get the date 28 Sep 2011 and I have to find out the date of the first Monday after this date.

Ammadas answered 27/9, 2011 at 7:5 Comment(3)
You can use use Calendar class for that BTW how you want to pass the date?Telecast
This question seems to crop up a lot.. why is that?Gonsalez
Passing data is irrelevant as I already set up the alarm service. I just need to find out the first Monday to set the alarms in the right manner.Ammadas
F
10

Do like this:

GregorianCalendar date = new GregorianCalendar( year, month, day ); 

while( date.get( Calendar.DAY_OF_WEEK ) != Calendar.MONDAY )
  date.add( Calendar.DATE, 1 );

You can now extract the year, day and month from date. Remember that month is 0 based (e.g. January = 0, Febuary = 1, etc.) and day is not.

Forwarder answered 27/9, 2011 at 7:14 Comment(1)
FYI: this code uses the old legacy date-time classes, now supplanted by the java.time classes.Catlike
C
4

tl;dr

LocalDate.now( ZoneId.of( "America/Montreal" ) )                   // Capture the current date as seen by the people in a certain region (time zone).
         .with( TemporalAdjusters.next( DayOfWeek.WEDNESDAY ) ) ;  // Move to the following Wednesday.

Avoid .Date/.Calendar

The java.util.Date & .Calendar classes bundled with Java/Android are notoriously troublesome. Avoid them.

java.time – LocalDate

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

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.

The time zone is crucial in determining the day and day-of-week. Use proper time zone names, never the 3 or 4 letter codes.

If you ignore time zone, the JVM’s current default time zone will be applied implicitly. This means different outputs when moving your app from one machine to another, or when a sys admin changes the time zone of host machine, or when any Java code in any thread of any app within the same JVM decides to call setDefault even during your app‘s execution.

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

TemporalAdjuster

Use a TemporalAdjuster to get next day-of-week. We can use an implementation in the TemporalAdjusters (note the plural 's') class: next( DayOfWeek ). Pass an object from the handy DayOfWeek enum.

LocalDate nextWednesday = today.with( TemporalAdjusters.next( DayOfWeek.WEDNESDAY ) );

If you wanted today to be found if it is a Wednesday, then call the similar adjuster TemporalAdjusters.nextOrSame( DayOfWeek ).


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?


Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This section left intact as history.

Here is example code using Joda-Time 2.7.

Get the time zone you desire/expect. If working in UTC, use the constant DateTimeZone.UTC.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );

Get the date-time value you need. Here I am using the current moment.

DateTime dateTime = DateTime.now( zone );

Specify the future day-of-week you want. Note that Joda-Time uses the sensible # 1 for first day of week, rather than zero-based counting found in java.util.Calendar. First day of week is Monday, per international norms and standards (not Sunday as is common in United States).

int dayOfWeek = DateTimeConstants.SATURDAY;

The withDayOfWeek command may go back in time. So we use a ternary operator (?:) to make sure we go forwards in time by adding a week as needed.

DateTime future = ( dateTime.getDayOfWeek() < dayOfWeek )
        ? dateTime.withDayOfWeek( dayOfWeek )
        : dateTime.plusWeeks( 1 ).withDayOfWeek( dayOfWeek );

You may want to adjust the time-of-day to the first moment of the day to emphasize the focus on the day rather than a particular moment within the day.

future = future.withTimeAtStartOfDay(); // Adjust time-of-day to first moment of the day to stress the focus on the entire day rather than a specific moment within the day. Or use `LocalDate` class.

Dump to console.

System.out.println( "Next day # " + dayOfWeek + " after " + dateTime + " is " + future );

When run.

Next day # 6 after 2015-04-18T16:03:36.146-04:00 is 2015-04-25T00:00:00.000-04:00

LocalDate

If you only care about the date without any time of day, you can write similar code with the LocalDate class rather than DateTime. The "Local" means the date could apply to any locality, rather than having a specific time zone.

LocalDate localDate = new LocalDate( 2011 , 9 , 28 );

int dayOfWeek = DateTimeConstants.MONDAY;
LocalDate future = ( localDate.getDayOfWeek() < dayOfWeek )
        ? localDate.withDayOfWeek( dayOfWeek )
        : localDate.plusWeeks( 1 ).withDayOfWeek( dayOfWeek );

When run.

Next day # 1 after 2011-09-28 is 2011-10-03
Catlike answered 19/4, 2015 at 1:42 Comment(0)
H
1

Get Next Monday from the date given.

  //code provided by MadProgrammer at https://mcmap.net/q/473041/-get-first-next-monday-after-certain-date/24177555#24177555

  Calendar date1 = Calendar.getInstance();
  date1.set(2014, 05, 12);

  while (date1.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {

    date1.add(Calendar.DATE, 1);
}

System.out.println(date1.getTime());

Which outputted...

Mon Jun 16 16:22:26 EST 2014
Hunchbacked answered 12/6, 2014 at 6:52 Comment(0)
T
1

I recently developed Lamma which is designed to solve this use case. Simply call next(DayOfWeek.MONDAY) on io.lamma.Date object will return the next Monday.

System.out.println(new Date(2014, 6, 27).next(DayOfWeek.MONDAY));   // Date(2014,6,30)
Tawnyatawsha answered 27/6, 2014 at 18:15 Comment(2)
The project looks cool. Where do you suggest we use it? For what types of apps it's designed for?Ammadas
Thanks. The project is designed for complicated date calculation and schedule generation. But not for time or timezone related calculations.Tawnyatawsha
T
0

you can use strtotime():

date('Y-m-d H:i:s', strtotime( "Next Monday", strtotime('28 Sep 2011')) );
Testy answered 30/4, 2012 at 1:21 Comment(1)
strtotime()..is'nt it php?Hunchbacked

© 2022 - 2024 — McMap. All rights reserved.