Get the next date by specifying the day of week - java

I need to use calendar to do this approach, basicly i get the specific day of week (1,2,3) each int represents a day of week(Monday,Tuesday) not in this order, but the logic is this.
What i need is to get the date of the next day of week, imagine today is Monday, and the user select Wednsesday, i need to get the date of the next Wednesday.
My logic is this at the moment:
calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
dateMatch = calendar.getTime();
day of week is passed from a slidePicker, and represents the specific day of week, this DAY_OF_WEEK doesn't work, if i put Wednseday he gives me 6

Although your question text only says to find next dayOfWeek, your code also includes a time of day, in the form of hour and minute.
Assuming you want the first future occurrence of that combination, i.e. dayOfWeek, hour, and minute, that means that if today is that dayOfWeek, you either want today if time of day is later than now, or next week if time of day is earlier than now.
You can do that like this:
int dayOfWeek = Calendar.WEDNESDAY;
int hour = 10; // 10 AM
int minute = 0;
Calendar cal = Calendar.getInstance(); // Today, now
if (cal.get(Calendar.DAY_OF_WEEK) != dayOfWeek) {
cal.add(Calendar.DAY_OF_MONTH, (dayOfWeek + 7 - cal.get(Calendar.DAY_OF_WEEK)) % 7);
} else {
int minOfDay = cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE);
if (minOfDay >= hour * 60 + minute)
cal.add(Calendar.DAY_OF_MONTH, 7); // Bump to next week
}
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(cal.getTime()); // Prints: Wed May 10 10:00:00 EDT 2017

tl;dr
To get the next Wednesday after today, or stick with today’s date if already a Wednesday.
LocalDate.now( ZoneId.of( "Africa/Tunis" ) )
.with( TemporalAdjusters.nextOrSame( DayOfWeek.WEDNESDAY ) )
java.time
Use modern java.time classes that supplanted the troublesome old legacy date-time classes such as Calendar.
Use DayOfWeek enum objects to represent Monday-Sunday. Use smart objects rather than dumb integers to represent your day-of-week intention. Makes your code more self-documenting, ensures valid values, and provides type-safety.
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 ) ;
Use a TemporalAdjuster implementation such as TemporalAdjusters.nextOrSame to move to another date.
TemporalAdjuster ta = TemporalAdjusters.nextOrSame( DayOfWeek.WEDNESDAY ) ;
LocalDate nextOrSameWednesday = today.with( ta ) ;
If working with moments, use ZonedDateTime class rather than the awful Calendar class. Some idea as above, let the TemporalAdjuster do the heavy-lifting. But keep in mind that the time-of-day may be altered if that time-of-day is invalid for that new date such as during a Daylight Saving Time (DST) cut-over.
ZoneId z = ZoneId.of( "Pacific/Auckland" );
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
TemporalAdjuster ta = TemporalAdjusters.nextOrSame( DayOfWeek.WEDNESDAY ) ;
ZonedDateTime zdtSameOrNextWednesday = zdt.with( ta ) ;
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, 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.

Related

Getting last Day of Month XY with Calendar Java

I need to get the last date of a given month, in my case I need to get the last Date of June. My code is following:
cal.set(Calendar.DAY_OF_MONTH,
Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH));
int month = cal.get(Calendar.MONTH) + 1;
if (month <= 6) {
cal.set(Calendar.DAY_OF_YEAR, Calendar.getInstance()
.getActualMaximum(Calendar.JUNE));
return (Calendar) cal;
} else {
cal.set(Calendar.DAY_OF_YEAR, Calendar.getInstance()
.getActualMaximum(Calendar.DAY_OF_YEAR));
return (Calendar) cal;
}
At first I get the actual month and wether it's the first half of the year or the second in need another date, always the last date of that half year. With the code above the return is
2015-01-31
and not 2015-06-31 as I thought it should be. How could I possibly fix this?
Your code is all over the place at the moment, unfortunately - you're creating new calendars multiple times for no obvious reason, and you're calling Calendar.getActualMaximum passing in the wrong kind of constant (a value rather than a field).
You want something like:
int month = cal.get(Calendar.MONTH) <= Calendar.JUNE
? Calendar.JUNE : Calendar.DECEMBER;
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calenday.DAY_OF_MONTH));
return cal;
However, I would strongly recommend using java.time if you're on Java 8, and Joda Time if you're not - both are much, much better APIs than java.util.Calendar.
java.time
Much easier now with the modern java.time classes. Specifically, the YearMonth, Month, and LocalDate classes.
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, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
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 ) ;
YearMonth
With a LocalDate in hand, get the year-month of that date.
YearMonth ym = YearMonth.from( ld ) ;
See which half year it is in.
Set < Month > firstHalfOfYear = EnumSet.range( Month.JANUARY , Month.JUNE ); // Populate the set with first six months of the year.
boolean isFirstHalf = firstHalfOfYear.contains( ym.getMonth() );
Knowing which half of the year, get the end of June or the end of December in the same year.
LocalDate result = null;
if ( isFirstHalf ) {
result = ym.withMonth( Month.JUNE.getValue() ).atEndOfMonth();
} else { // Else in last half of year.
result = ym.withMonth( Month.DECEMBER.getValue() ).atEndOfMonth();
}
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.

Compare Date and Time in Java

how to compare three date/time values in java?
Currently i use Date objects
I mean:
Date1 - today, 10:00PM
Date2 - tomorrow, 5:00AM
Date3 - current time
Is date3 between date1 and date2, respect date AND time?
date1.compareTo(date3) * date2.compareTo(date3) > 0
and
date1.after(date3) && date2.before(date3)
are not working.
I use this code in Android App, and if i set my time to 11.30AM, it still returns true for above conditions. If i use Time-objects and 2nd method, it doesn't recognise my time span is between 2 days.
Any idea?
EDIT: To make it exact, here is my current code. app is something like an alarm clock.
// Current Date/Time
Date now = Calendar.getInstance().getTime();
// Time when user goes to bed (current day)
Date sleep = new Date(now.getYear(), now.getMonth(), now.getDate(), Shours, Sminutes);
// Time when user wakes up (next day)
// Get Next Day's Date and set Time
Calendar wk = Calendar.getInstance();
wk.setTime(sleep);
wk.set(Calendar.HOUR_OF_DAY, Whours);
wk.set(Calendar.MINUTE, Wminutes);
// tomorrow
wk.add(Calendar.DATE, 1);
// and convert to date
Date wake = wk.getTime();
// Compare
if(now.after(sleep) && now.before(wake)) {
Log.d("uSleep", "Debug: Night time");
}
else {
Log.d("uSleep", "Debug: Day Time");
}
Maybe it's still too hard to understand. Image you go to bed at 10PM and you get up at 5AM. Now how to find out if you're sleeping by comparing your "go to bed"-time and you "get up"-time to the current time. I need to use "tomorrow" for your "get up"-time, otherwise java seems to compare all times for the same day, which is impossible.
tl;dr
Interval.of(
start ,
stop
).contains(
ZonedDateTime.now( ZoneId.of( "America/Montreal" ) )
.toInstant()
)
Details
The question is confusing, but seems to be…
How do I tell if a particular moment occurs within a span of time?
java.time
I mean: Date1 - today, 10:00PM Date2 - tomorrow, 5:00AM Date3 - current time
A time zone is crucial in determining “today” and “tomorrow”. 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.
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" );
ZonedDateTime now = ZonedDateTime.now( z );
To get the same date with another time-of-day, extract LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone. Specify desired time-of-day with LocalTime. Combine with ZoneId to get a ZonedDateTime.
LocalDate today = now.toLocalDate() ;
LocalTime tenPm = LocalTime.of( 22 , 0 ) ; // 10 PM is 22:00.
ZonedDateTime tenPmToday = ZonedDateTime.of( today , tenPm , z ) ;
To get tomorrow, add one day to today's date.
LocalDate tomorrow = ld.plusDays( 1 ) ;
LocalTime fiveAm = LocalTime.of( 5 , 0 ) ;
ZonedDateTime fiveAmTomorrow = ZonedDateTime.of( tomorrow ,fiveAm , z ) ;
Compare
To compare, call the isBefore, isEqual, and isAfter methods.
Boolean contains = ( ! now.isBefore( tenPmToday ) ) && now.isBefore( fiveAmTomorrow ) ;
Of course, now will always be before tomorrow, so I'm not sure of your intentions here.
org.threeten.extra.Interval
You may find the Interval class useful for this work, from the ThreeTen-Extra project listed below. This class stores a pair of Instant objects, and has some handy comparison methods such as contains.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Interval interval = Interval.of( tenPmToday.toInstant() , fiveAmTomorrow.toInstant() ) ;
Boolean contains = interval.contains( now.toInstant() ) ;
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?
Java SE 8, Java SE 9, 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
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
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.
Joda-Time
Update: the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
The best way is to use the Joda-Time library, rather than the java.util.Date/.Calendar classes which are notoriously troublesome, confusing, and flawed.
Span Of Time
In Joda-Time you can represent a span of time in three ways: Interval, Period, and Duration. In this case, we need Interval, defined by a pair of specific points in the timeline, with the half-open [) approach where the beginning is inclusive and the ending exclusive.
The pair of specific points, as well as the current moment now, are all represented by the DateTime class. Unlike a java.util.Date, a DateTime knows its own assigned time zone. If unspecified, the JVM’s current default time zone will be applied. So generally better to specify.
Example Code
Some example code using Joda-Time 2.5.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone );
DateTime bedtime = now.withTime( 22, 0, 0, 0 ); // Today’s bedtime. May be past, future, or this very moment now.
DateTime risetime = bedtime.plusHours( 7 ); // 05:00 next morning.
Interval sleepInterval = new Interval( bedtime, risetime );
boolean asleep = sleepInterval.contains( now ); // Half-Open "[)" comparison, beginning is inclusive, ending exclusive.

Check if the Calendar date is a sunday

I am trying to figure out how to make my program count the number of Sundays in a week.
I have tried the following thing:
if (date.DAY_OF_WEEK == date.SUNDAY) {
System.out.println("Sunday!");
}
Yet it does not seem to work?
When I try to System.out.Println the date.DAY_OF_WEEK I get: 7
Does anyone know how I can check if the current calendar date is Sunday?
UPDATE FOR MORE INFORMATION
firt of all the date.DAY_OF_WEEK is a Calendar object!
i made sure to set the Calendar object date to a sunday
The system out print where i get 7 is what it returns to me when i try to run date.DAY_OF_MONTH even if the day it set to a sunday
2nd UPDATE TO ALEX
This is more or less my code
Calendar startDate = Calendar.getInstance();
startDate.set(2012, 12, 02);
if (startDate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
System.out.println("true");
}else {
System.out.println("FALSE");
}
Calendar cal = ...;
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
System.out.println("Sunday!");
}
Calendar.DAY_OF_WEEK always equals to 7 no matter what instance of Calendar you are using (see this link), it is a constant created to be used with the Calendar.get() method to retrieve the correct value.
It is the call to Calendar.get(Calendar.DAY_OF_WEEK) that will return the real day of week. Besides, you will find useful values in the Calendar class like Calendar.SUNDAY (and the other days and months) in order for you to be more explicit in your code and avoid errors like JANUARY being equal to 0.
Edit
Like I said, the Calendar class does contains useful constants for you to use. There is no month number 12 they start at 0 (see above), so DECEMBER is month number 11 in the Java Date handling.
Calendar startDate = Calendar.getInstance();
startDate.set(2012, Calendar.DECEMBER, 02);
if (startDate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
System.out.println("true");
} else {
System.out.println("FALSE");
}
Will print true of course.
Note: the Joda-Time project is now in maintenance mode. See this answer if you don't have to work with legacy code.
If you have to work with date or time a lot, you might want to try using Joda-Time.
Your code would look something like this:
LocalDate startDate = new LocalDate(2012, 12, 2);
int day = startDate.dayOfWeek().get(); // gets the day of the week as integer
if (DateTimeConstants.SUNDAY == day) {
System.out.println("It's a Sunday!");
}
You can also get a text string from dayOfWeek():
String dayText = startDate.dayOfWeek().getAsText();
will return the string "Sunday".
tl;dr
boolean todayIsSunday = LocalDate.now( ZoneId.of( "America/Montreal" ) ).getDayOfWeek().equals( DayOfWeek.SUNDAY ) ;
java.time
The other Answers are outdated. The modern approach uses java.time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
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 during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If critical, confirm the zone with your user.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-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 code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.
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. Ditto for Year & YearMonth.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
DayOfWeek
For any LocalDate, you can obtain its day-of-week as a DayOfWeek object. The DayOfWeek enum automatically instantiates seven objects, one for each day of the week.
boolean isSunday = ld.getDayOfWeek().equals( DayOfWeek.SUNDAY ) ;
One Sunday per week
count the number of Sundays in a week.
That would be 1, always one Sunday per week.
If your goal is finding the next Sunday, use a TemporalAdjuster defined in TemporalAdjusters class.
TemporalAdjuster ta = TemporalAdjusters.nextOrSame( DayOfWeek.SUNDAY ) ;
LocalDate nextOrSameSunday = ld.with( ta ) ;
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….

Java Calendar.add gives wrong year

My program takes the current date and then, in a loop, adds a week to that date and prints out the new date. Something like:
Calendar cal = Calendar.getInstance();
for (int i=0; i < 52; i++) {
cal.add(Calendar.DATE, 7);
// print date out
}
The add method works the way I expect it to until it reaches Dec 30, at which point the year jumps from 2012 to 2013.
so, using today's date of 4/16/2012, i tested a few different inputs:
this - cal.add(Calendar.DATE, 38*7);
yields- "date:1/7/2013"
this - cal.add(Calendar.DATE, 37*7);
yields- "date:12/31/2013"
this - cal.add(Calendar.DATE, 37*7-1);
yields- "date:12/30/2013"
this - cal.add(Calendar.DATE, 37*7-2);
yields- "date:12/29/2012"
so i notice that the year is correct up until dec 30 and dec 31, and then it corrects itself again when it gets back to january. is there a reason why it does this? does it have anything to do with 2012 being a leap year or am i misunderstanding the add method
Did you use SimpleDateFormat to print the date and use YYYY to produce the year? If so, that is where the problem lies. Because YYYY produces the week-year and not the calendar year. And as 30/12/2012 is in calendar week 1 of 2013, YYYY produces 2013. To get the calendar year, use yyyy in your SimpleDateFormat format string.
See https://bugs.openjdk.java.net/browse/JDK-8194625
tl;dr
Use modern java.time classes, never the terrible legacy classes such as Calendar.
LocalDate // Represent a date-only value with `LocalDate`, without time-of-day and without time zone.
.now( // Capture the current date.
ZoneId.systemDefault() // Specify your desired/expected time zone explicitly.
) // Returns a `LocalDate` object.
.plusWeeks( 1 ) // Add a week, producing a new `LocalDate` object with values based on the original, per the immutable objects pattern.
.toString() // Generate text representing this date value in standard ISO 8601 format of YYYY-MM-DD.
2019-01-23
java.time
The modern approach uses the java.time classes.
The Calendar and GregorianCalendar classes are terrible, badly designed with flaws. Avoid them. Now replaced specifically by the ZonedDateTime class.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
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 during runtime(!), 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 2-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 ) ;
To generate text representing that date value in standard ISO 8601 format, simply call toString.
String output = today.toString() ;
Date math is easy, with various plus… & minus… methods.
LocalDate weekLater = today.plusWeeks( 1 ) ;
You can also define a span of time as a Period or Duration. Then add that.
Period p = Period.ofWeeks( 1 ) ;
LocalDate weekLater = today.plus( p ) ;
Your example
Let's test out your example dates.
LocalDate ld = LocalDate.of( 2012 , Month.APRIL , 16 ) ;
Period period38Weeks = Period.ofWeeks( 38 ) ;
Period period37Weeks = Period.ofWeeks( 37 ) ;
Period period37WeeksLess1Days = period37Weeks.minusDays( 1 ) ;
Period period37WeeksLess2Days = period37Weeks.minusDays( 2 ) ;
LocalDate later_38 = ld.plus( period38Weeks ) ;
LocalDate later_37 = ld.plus( period37Weeks ) ;
LocalDate later_37_1 = ld.plus( period37WeeksLess1Days ) ;
LocalDate later_37_2 = ld.plus( period37WeeksLess2Days ) ;
Run code live at IdeOne.com. No problems. The 38th week is in 2013, while week 37 dates are in 2012.
later_38.toString(): 2013-01-07
later_37.toString(): 2012-12-31
later_37_1.toString(): 2012-12-30
later_37_2.toString(): 2012-12-29
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, Java SE 11, and later - 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
Most 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.
It should be:
cal.add(Calendar.DAY_OF_YEAR, 7);
Calendar.DATE is same as Calendar.DAY_OF_MONTH.

Comparing Dates and Using Calendar class and Date class In Java

I'd love your help understanding the following:
Assume that I have a Value of type date
Date start;
How can I chack whether the current date is a week or more since the date of start ?
I tried to chack Java API on the web, and I got confused.
Thank you.
Using calendar you can add days to the start date and then compare it to the current date.
For example:
Date start = Calendar.getInstance().getTime();
start.setTime(1304805094L); // right now...
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, 7);
start.compareTo(cal.getTime());
I would use Joda time for that.
http://joda-time.sourceforge.net/
You can then use this method as a template for what you want to do. The method is an example from the Joda site:
public boolean isRentalOverdue(DateTime datetimeRented) {
Period rentalPeriod = new Period().withDays(2).withHours(12);
return datetimeRented.plus(rentalPeriod).isBeforeNow();
}
tl;dr
whether the current date is a week or more since the date of start ?
LocalDate.now().minusWeeks( 1 ).isAfter( someLocalDate )
java.time
The modern approach uses java.time classes.
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 );
Specify the other 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 ) ;
So, is the current date at least a week after the target date?
Calculate a week ago.
LocalDate weekAgo = today.minusWeeks( 1 ) ;
Compare with isBefore, isAfter, and isEqual methods.
Boolean isOverAWeekOld = ld.isBefore( weekAgo ) ;
Bonus: See if the target date is within the past week.
boolean inPastWeek = ( ! ld.isBefore( weekAgo ) ) && ld.isBefore( today ) ;
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?
Java SE 8, Java SE 9, 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, 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.

Categories