How to change date and fast time - java

I need to change the time of a date to 23.59.
I can do it but the fast time remain the same so the date is actually not changed.
*start is my starting date exemple 6th december 2017 at 9.31am
Calendar calendar = Calendar.getInstance();
calendar.setTime(start);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND,0);
start = calendar.getTime();
I have start date at 6th december 2017 at 23.59am but the fast time is still the same.
How can I do?

I recommend you stop using the Calendar class and use java.time, the modern Java date and time API for your task:
ZonedDateTime dateTime = ZonedDateTime.of(
2017, 12, 6, 9, 31, 0, 0, ZoneId.of("Canada/Newfoundland"));
// to change time to 0:00:00
dateTime = dateTime.truncatedTo(ChronoUnit.DAYS);
System.out.println("Changed to 0:00: " + dateTime);
// to change to end of day
dateTime = dateTime.with(LocalTime.MAX);
System.out.println("Changed to end of day: " + dateTime);
// if you need it without seconds
dateTime = dateTime.truncatedTo(ChronoUnit.MINUTES);
System.out.println("Changed to 23:59: " + dateTime);
This prints
Changed to 0:00: 2017-12-06T00:00-03:30[Canada/Newfoundland]
Changed to end of day: 2017-12-06T23:59:59.999999999-03:30[Canada/Newfoundland]
Changed to 23:59: 2017-12-06T23:59-03:30[Canada/Newfoundland]
The classes Date and Calendar are long outmoded. java.time is so much nicer to work with (it is also known as JSR-310).
I recommend you specify explicitly which time zone you want your time in. So fill in yours unless it happens to be Canada/Newfoundland. To use your JVM’s time zone setting use ZoneId.systemDefault(), but beware that this setting may be changed by other parts of your program or other programs running in the same JVM.
In case start is a Date you got from a legacy API that you do not want to change just now, start by converting it to java.time.Instant and do the remainder of your operations from there:
ZonedDateTime dateTime = start.toInstant().atZone(ZoneId.of("Canada/Newfoundland"));
The rest is the same as above. If the opposite was the case, you need to pass a Date to a legacy API at the end, the opposite conversion is:
start = Date.from(dateTime.toInstant());
What went wrong in your code?
There’s is nothing wrong with your code. At least on my computer it behaves as expected. I would be very surprised if it didn’t on yours. A bit of speculation: You may have noticed that the first and the last digits of the value of start.fastTime were the same, and this could have fooled you into thinking the value had not changed. If this was the problem, it may help you to add this line:
calendar.set(Calendar.MILLISECOND, 0);
This will make sure that fastTime ends in at least five zeroes, for example 1513206000000, and it will be more conspicuous that it has changed. Fortunately, the modern API offers the truncatedTo method, an easy way to obtain zeroes on the last places of your milliseconds value.
Links
Oracle tutorial trail: Date Time
Java Specification Request (JSR) 310

Related

Firestore - Creating a query where results are within last 7 days [duplicate]

I have a report created in Jasper Reports which ONLY recognizes java.util.Date's (not Calendar or Gregorian, etc).
Is there a way to create a date 7 days prior to the current date?
Ideally, it would look something like this:
new Date(New Date() - 7)
UPDATE: I can't emphasize this enough: JasperReports DOES NOT RECOGNIZE Java Calendar objects.
From exactly now:
long DAY_IN_MS = 1000 * 60 * 60 * 24;
new Date(System.currentTimeMillis() - (7 * DAY_IN_MS))
From arbitrary Date date:
new Date(date.getTime() - (7 * DAY_IN_MS))
Edit: As pointed out in the other answers, does not account for daylight savings time, if that's a factor.
Just to clarify that limitation I was talking about:
For people affected by daylight savings time, if by 7 days earlier, you mean that if right now is 12pm noon on 14 Mar 2010, you want the calculation of 7 days earlier to result in 12pm on 7 Mar 2010, then be careful.
This solution finds the date/time exactly 24 hours * 7 days= 168 hours earlier.
However, some people are surprised when this solution finds that, for example, (14 Mar 2010 1:00pm) - 7 * DAY_IN_MS may return a result in(7 Mar 2010 12:00pm) where the wall-clock time in your timezone isn't the same between the 2 date/times (1pm vs 12pm). This is due to daylight savings time starting or ending that night and the "wall-clock time" losing or gaining an hour.
If DST isn't a factor for you or if you really do want (168 hours) exactly (regardless of the shift in wall-clock time), then this solution works fine.
Otherwise, you may need to compensate for when your 7 days earlier doesn't really mean exactly 168 hours (due to DST starting or ending within that timeframe).
Use Calendar's facility to create new Date objects using getTime():
import java.util.GregorianCalendar;
import java.util.Date;
Calendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_MONTH, -7);
Date sevenDaysAgo = cal.getTime();
try
Date sevenDay = new Date(System.currentTimeMillis() - 7L * 24 * 3600 * 1000));
Another way is to use Calendar but I don't like using it myself.
Since no one has mentioned TimeUnit yet:
new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7))
Java 8 based solution:
new Date(
Instant.now().minus(7, ChronoUnit.DAYS)
.toEpochMilli()
)
Try this:
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, -7);
return c.getTime();
A determining "days" requires a time zone. A time zone defines when a "day" begins. A time zone includes rules for handling Daylight Saving Time and other anomalies. There is no magic to make time zones irrelevant. If you ignore the issue, the JVM's default time zone will be applied. This tends to lead to confusion and pain.
Avoid java.util.Date
The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. They are so bad that Sun/Oracle agreed to supplant them with the new java.time package in Java 8. Use either that or Joda-Time.
Joda-Time
Example code in Joda-Time 2.3.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" ); // Specify or else the JVM's default will apply.
DateTime dateTime = new DateTime( new java.util.Date(), timeZone ); // Simulate passing a Date.
DateTime weekAgo = dateTime.minusDays( 7 );
First Moment Of Day
Or, you may want to adjust the time-of-day to the first moment of the day so as to capture an entire day's worth of time. Call the method withTimeAtStartOfDay. Keep in mind this is usually 00:00:00 but not always.
Avoid the "midnight" methods and classes in Joda-Time. They are based on a faulty concept and are now deprecated.
DateTime dateTimeStart = new DateTime( new java.util.Date(), timeZone ).withTimeAtStartOfDay(); // Not necessarily the time "00:00:00".
DateTime weekAgo = dateTime.minusDays( 7 ).withTimeAtStartOfDay();
Convert To/From j.u.Date
As seen above, to convert from java.util.Date to Joda-Time merely pass the Date object to constructor of DateTime. Understand that a j.u.Date has no time zone, a DateTime does. So assign the desired/appropriate time zone for deciding what "days" are and when they start.
To go the other way, DateTime to j.u.Date, simply call the toDate method.
java.util.Date date = dateTime.toDate();
I'm not sure when they added these, but JasperReports has their own set of "functions" that can manipulate dates. Here is an example that I haven't tested thoroughly:
DATE(YEAR(TODAY()), MONTH(TODAY()), DAY(TODAY()) - 7)
That builds a java.util.Date with the date set to 7 days from today. If you want to use a different "anchor" date, just replace TODAY() with whatever date you want to use.
You can try this,
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, -7);
System.out.println(new java.sql.Date(c.getTimeInMillis()));
Due to the heated discussion:
The question may not have a proper answer w/o a designated timezone.
below it is some code to work w/ the default (and hence deprecated) timezone that takes into account the default timezone daylight saving.
Date date= new Date();
date.setDate(date.getDate()-7);//date works as calendar w/ negatives
While the solution does work, it is exactly as bogus as in terms of assuming the timezone.
new Date(System.currentTimeMillis() - 10080*60000);//a week has 10080 minutes
Please, don't vote for the answer.
I'm doing it this way :
Date oneWeekAgo = DateUtils.addDays(DateUtils.truncate(new Date(), java.util.Calendar.DAY_OF_MONTH), -7);

Loop a Task for one Year with GregorianCalendar

I have to write a program which shows a Timeplan about when to send emails.
The User is inputing a Start date and I have to show the timeplan for one year.
How do I loop the Task?
In this example the mails should be sent every 8 days.
if(recipient==0) {
System.out.println("send mail on this day:" +calendar.getTime());
calendar.add((GregorianCalendar.DAY_OF_YEAR),8);
return true;
}
I would like to loop the System.out.println and the calendar.add task until it is one year later.
edit: I have another case where it should send the emails every 16 days but when the day is a saturday or sunday it should send the mail on the following monday.
I did it like this but now I get more dates than I need.
if(empfaenger==1)
{
for (Date d=startDate; d.before(endDate); d.setTime(d.getTime() + (1000 * 60 * 60 * 24 * 8)))
{
if(calendar.get(calendar.DAY_OF_WEEK)==1)
{
calendar.add((GregorianCalendar.DAY_OF_YEAR),1);
System.out.println("mail will be sent on this day:"+calendar.getTime());
calendar.add((GregorianCalendar.DAY_OF_YEAR), 16);
}
else if(calendar.get(calendar.DAY_OF_WEEK)==7)
{
calendar.add((GregorianCalendar.DAY_OF_YEAR), 2);
System.out.println("mail will be sent on this day:"+calendar.getTime());
calendar.add((GregorianCalendar.DAY_OF_YEAR),16);
}
else
{
System.out.println("mail will be sent on this day:"+calendar.getTime());
calendar.add((GregorianCalendar.DAY_OF_YEAR),16);
}
//System.out.println(calendar.getTime;)
}
}
Here is a sample using java.time api from java 8 , it's much more easier to understand and use compered to calendar or date classes :
static void sendEveryEightDays(){
LocalDateTime timeToSendEmail= LocalDateTime.now();
LocalDateTime afterAYear = timeToSendEmail.plusYears(1);
while(timeToSendEmail.isBefore(afterAYear)){
System.out.println("SendTheEmail "+timeToSendEmail.toString());
timeToSendEmail=timeToSendEmail.plusDays(8);
}
}
if you want to take the user's time zone into consideration you can use ZonedDateTime instated off LocalDateTime :
static void sendEveryEightDays(ZoneId userTimeZone){
ZonedDateTime timeToSendEmail= ZonedDateTime.now(userTimeZone);
ZonedDateTime afterAYear = timeToSendEmail.plusYears(1);
while(timeToSendEmail.isBefore(afterAYear)){
System.out.println("SendTheEmail "+timeToSendEmail.toString());
timeToSendEmail=timeToSendEmail.plusDays(8);
}
}
I wonder why teachers are still teaching the old API (Date, Calendar and SimpleDateFormat), because they have lots of problems and design issues, and they're being replaced by the new APIs. (Java 8 was released in 2014, btw).
Anyway, if you have a GregorianCalendar, you can convert it to the new java.time classes and do the rest with them.
First, you can use the calendar to create an Instant:
Instant instant = Instant.ofEpochMilli(calendar.getTimeInMillis());
The only problem is that, if you create a Calendar and set the day, month and year, it will have the current time (hour/minute/seconds), so the Instant above will have the current time in UTC. If that's ok, you can convert this instant to your timezone:
ZoneId zone = ZoneId.of("America/Sao_Paulo");
ZonedDateTime start = instant.atZone(zone);
I used America/Sao_Paulo, but you can change to the timezone that makes sense to your system. The API uses IANA timezones names (always in the format Region/City, like America/Sao_Paulo or Europe/Berlin).
Avoid using the 3-letter abbreviations (like CST or PST) because they are ambiguous and not standard.
You can get a list of available timezones (and choose the one that fits best your system) by calling ZoneId.getAvailableZoneIds(). You can also use the system's default if you want (ZoneId.systemDefault()), but note that this can be changed without notice, even at runtime, so it's always better to specify which timezone you're using. If you want to work with dates in UTC, you can use the built-in constant ZoneOffset.UTC.
The code above will create a ZonedDateTime with the calendar's date and time adjusted to the specified timezone. Just reminding that, if you do something like this:
Calendar calendar = new GregorianCalendar();
calendar.set(2017, 7, 12);
The date will be equivalent to August 12th 2017 (because months in the Calendar API start at zero, so month 7 is August), and the time will be the current time when the calendar is created.
If you want to specify the hour, you have some options to adjust it:
// change the hour/minute/second to 10:20:45
start = start.with(LocalTime.of(10, 20, 45));
// change just the hour to 10
start = start.withHour(10);
// set to start of the day
start = start.toLocalDate().atStartOfDay(zone);
With this, you can change the time (and also date) fields accordingly. Check the javadoc and Oracle's tutorial to see all the options available. The method atStartOfDay is better because it takes care of Daylight Saving Time changes (depending on DST shift, the day can start at 1AM instead of midnight, and this method takes care of all the details).
If you don't want to rely on Calendar, you can also create the date directly:
// creating August 12th 2017, at 10:00
start = ZonedDateTime.of(2017, 8, 12, 10, 0, 0, 0, zone);
Note that August is month 8 (one of the best and most obvious improvements from the old API).
Now that you have the starting date, you can loop through a whole year and check the dates according to your rules. I'm using the example of sending the email each 16 days and adjust to next monday if it's a weekend:
ZonedDateTime d = start;
// ends in 1 year - this method already takes care of leap years
ZonedDateTime end = start.plusYears(1);
while (end.isAfter(d)) {
d = d.plusDays(16);
if (d.getDayOfWeek() == DayOfWeek.SUNDAY || d.getDayOfWeek() == DayOfWeek.SATURDAY) {
// weekend, adjust to next monday
d = d.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
}
// send email
}
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes.
The only difference from Java 8 is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
As #BasilBourque reminded me in the comments, you can also convert a GregorianCalendar to a ZonedDateTime using the toZonedDateTime() method (this will use the calendar's timezone - usually the system's default, if you don't set it). You can also convert it to an Instant using the toInstant() method. The only restriction is that those methods are only available in Java 8 (so, if you're using ThreeTen Backport, just use the way it's described above).

How do I add one day to a Calendar object and also account for daylight savings time?

I am trying to create a time limit for objects in a list. This could mean that the objects shelf life could be 23, 24 or 25 hours. Are there any Java libraries that could be useful? This is what I have so far.
My problem is that when I create a record at 9:30 am for example, it must be removed at 9:30 am on the following day. I get discrepancies when it is during the days which DST takes effect. The record is is either deleted at 8:30 or 10:30 depending if I spring forward or backward.
//baseValue = object that I want to check
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, -1);
if(baseValue.getTime() < c.getTime()){
array.remove(baseValue);
}
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, including difficulty to deal with DST changes, and they're being replaced by the new APIs.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
To take care of DST changes, the ideal class is ZonedDateTime, which represents a date and time in a specific timezone. I also use the ZoneId class, which represents the timezone itself.
I'm using my timezone (America/Sao_Paulo), because here we have DST as well, but you can replace with yours (more on that below):
// create a date 1 day before DST change in Sao Paulo, at 9 AM
ZoneId zone = ZoneId.of("America/Sao_Paulo");
ZonedDateTime z = ZonedDateTime.of(2017, 10, 14, 9, 0, 0, 0, zone);
// get the next day, at 9 AM
ZonedDateTime nextDay = z.plusDays(1);
System.out.println(z);
System.out.println(nextDay);
The output is:
2017-10-14T09:00-03:00[America/Sao_Paulo]
2017-10-15T09:00-02:00[America/Sao_Paulo]
Note that the offset changed from -03:00 to -02:00 - it's due to DST starting in São Paulo timezone (clocks move forward 1 hour). But also note that the time (9 AM) was preserved correctly.
If we take the difference in hours, we can see that it's correct:
System.out.println(ChronoUnit.HOURS.between(z, nextDay));
The output is:
23
Which correctly means that 23 hours has passed between those 2 dates (because of clocks shifting 1 hour forward, so 1 hour is "lost").
In your case, you need to know if 1 day has already passed, so you just call:
long days = ChronoUnit.DAYS.between(z, nextDay);
In this case, days will be 1 (even if the difference in hours calculated above is 23, because the API is smart enough to consider DST effects).
So in your case, you just need to check if the difference in days is 1 (or greater than 1, I don't know) and do all that it needs to be done.
If you need to get the current date/time, you can call ZonedDateTime.now(zone).
To use your timezone instead of mine, first note that the API uses IANA timezones names (always in the format Continent/City, like America/Sao_Paulo or Europe/Berlin).
Avoid using the 3-letter abbreviations (like CST or PST) because they are ambiguous and not standard.
You can get a list of timezones names with ZoneId.getAvailableZoneIds() - then choose the one that fits best to your case.
You can also use ZoneId.systemDefault() - it returns the system's default timezone. But this can be changed without notice - even at runtime - so it's recommended to use an explicit timezone.

Java Calendar Configuration

I am using the Calendar object as follows:
Calendar calendar = new GregorianCalendar();
calendar.set(Calendar.HOUR_OF_DAY, 24);
calendar.get(Calendar.HOUR_OF_DAY)
I want the result of this to be 24, as opposed to 0. Is this possible?
First of all, the time 24:00 is a valid time according to ISO-8601 and means midnight start at the next day.
java.util.GregorianCalendar does not support the hour 24. Please feel free to study following example code with my comments:
// By default lenient behaviour with overflow of 24:00 to next day
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
GregorianCalendar gcal = new GregorianCalendar(2014, Calendar.AUGUST, 17, 0, 0, 0);
gcal.set(Calendar.HOUR_OF_DAY, 24);
System.out.println("HOUR_OF_DAY: " + gcal.get(Calendar.HOUR_OF_DAY)); // 0
System.out.println(sdf.format(gcal.getTime())); // 2014-08-14 00:00
// now switch to strict mode
gcal.setLenient(false);
gcal.set(Calendar.HOUR_OF_DAY, 24);
gcal.getTime(); // triggers recomputation which will fail with following abort
// abort relates to set()-method => java.lang.IllegalArgumentException: HOUR_OF_DAY
Most other libraries do not support setting the time to 24:00, too. Neither Java-8-time nor its predecessor Joda-Time give support. However, Java-8-time can parse such times but never set.
My library Time4J partially allows setting this time, namely for the type PlainTime which indeed has an extended value range from 00:00 until 24:00 (inclusive). However, I have decided to handle it differently for the type PlainTimestamp(combination of calendar date and wall time) because I want to preserve a bijective unique mapping between timestamp and a single incrementing counter (otherwise the values 2014-08-17 24:00 and 2014-08-18 00:00 would stand for the same timestamp counter causing problems in sorting). The Time4J-solution for this problem is here automatic normalization (with overflow similar to lenient behaviour in the class GregorianCalendar).
If you set the field Calendar.HOUR_OF_DAY to be 24, then it is set to 0 of the next day.
the 24th hour of a day does not exist.
I think the command
Calendar.get(Calendar.HOUR_OF_DAY);
does the conversion from am/pm to 24H so you don't need to add anything else.

How can I parse a weekday and time object to the next logical date from today?

I have a date in the string that looks like MON 07:15. I'm trying to parse this to a Date using this snippet of code:
System.out.println(new SimpleDateFormat("E kk:mm").parse("MON 07:15"));
Using the above code, prints a date that reads:
Mon Jan 05 07:15:00 EET 1970
I'd like the parse the date string to the next upcoming date. At the time of posting, my local date and time is Fri Aug 08 11:45:00 EEST 2014 and the next Monday will be on the 11th so the resultant date that I'm looking for is Mon Aug 11 07:15:00 EEST 2014. How can I parse this?
The day and time object that I'll be parsing will always be in the future.
I would separate parsing from everything else.
Parse the value as you're already doing, which gives you a date in the wrong year.
From that, take the time of day and the day of week - those are the important things. You can throw everything else away.
Next, take the current date and time, and perform whatever operations you need to in order to get to the right date/time. You should consider:
What time zone are you interested in?
If the current time is 06:00 on a Monday and you've been asked for 07:15 on a Monday, does that mean today or next Monday?
If the current time is 08:00 on a Monday and you've been asked for 07:15 on a Monday, does that mean today or next Monday?
By separating out the parsing from the computations, you can make the testing simpler two: test each of the operations separately. I'd advise using a clock abstraction of some kind to indicate "an object which can get you the current instant in time" - that way you can test all kinds of combinations of "desired day/time" and "current day/time".
Ideally, use java.time from Java 8 or Joda Time - both are much nicer than the java.util.* API.
Are you looking something like following?
DateFormat df = new SimpleDateFormat("E kk:mm");
Date date = df.parse("MON 07:15");
Date today = new Date();
Calendar calendar = Calendar.getInstance();
Calendar calendar1 = Calendar.getInstance();
calendar.setTime(today);
calendar1.setTime(date);
if (calendar.get(Calendar.DAY_OF_WEEK) == calendar1.get(Calendar.DAY_OF_WEEK)) {
String time = df.format(today);
Date t1 = df.parse(time);
if (t1.before(date)) {
calendar.set(Calendar.HOUR, calendar1.get(Calendar.HOUR));
calendar.set(Calendar.MINUTE, calendar1.get(Calendar.MINUTE));
calendar.set(Calendar.SECOND, 0);
System.out.println(calendar.getTime());
} else {
calendar.add(Calendar.DATE, 7);
calendar.set(Calendar.HOUR_OF_DAY, calendar1.get(Calendar.HOUR));
calendar.set(Calendar.MINUTE, calendar1.get(Calendar.MINUTE));
calendar.set(Calendar.SECOND, 0);
System.out.println(calendar.getTime());
}
} else {
int toDay = calendar.get(Calendar.DAY_OF_WEEK);
int givenDay = calendar1.get(Calendar.DAY_OF_WEEK);
int count = 7 - toDay + givenDay;
calendar.add(Calendar.DAY_OF_MONTH, count);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.HOUR_OF_DAY, calendar1.get(Calendar.HOUR));
calendar.set(Calendar.MINUTE, calendar1.get(Calendar.MINUTE));
System.out.println(calendar.getTime());
}
Out put:
Mon Aug 11 07:15:00 IST 2014
Leave me a comment telling me whether I got your question correct.
This answer addresses the second part, getting the next logical date from today.
Avoid .Date/.Calendar
The java.util.Date & .Calendar classes bundled with Java are notoriously troublesome. Avoid them.
Joda-Time or java.time
I suggest learning how to use a sophisticated date-time library. In Java that means either:
Joda-Time
java.time (built into Java 8, inspired by Joda-Time).
Time Zone
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.
Example Code To Get Next Day-Of-Week
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

Categories