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.
You can find the next Monday's date easily with Python's datetime library and the timedelta object. You just need to take today's date. Then subtract the number of days which already passed this week (this gets you 'last' monday).
A slightly different method – The date. weekday() function gives your an index of the day of the week (where Monday is 0 and Sunday is 6). You can use this value to directly calculate the which date any day of the week will fall on.
isoweekday() to get a weekday of a given date in Python Use the isoweekday() method to get the day of the week as an integer, where Monday is 1 and Sunday is 7. i.e., To start from the weekday number from 1, we can use isoweekday() in place of weekday() . The output is 1, which is equivalent to Monday as Monday is 1.
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.
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.
The java.util.Date & .Calendar classes bundled with Java/Android are notoriously troublesome. Avoid them.
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.
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 )
.
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With