Java Calendar get Xº day of the week of month - java

I'm need to do a method that returns the position of actual day in the next month.
for today (20/12/2016)
I need to call this method whit today date
The return given must to be (17/01/2016)
This method must return the third Tuesday of the next month
Is the 4 week of this month, but I need the Third Tuesday.
I try to use Calendar.MONTH, Calendar.WEEK_OF_MONTH, Calendar.DAY_OF_WEEK but I can't get the third, I always get the fourth.
Some thing like this:
public static Date getNextMonthDayOfWeel(Date d) {
Calendar c = Calendar.getInstance();
c.setTime(d);
int week = c.get(Calendar.WEEK_OF_MONTH);
int day = c.get(Calendar.DAY_OF_WEEK);
//// this block
if(!firstWeekOfMonthHad(day)){
week++;
}
//// this block
c.setFirstDayOfWeek(Calendar.SUNDAY);
c.add(Calendar.MONTH, 1);
c.set(Calendar.WEEK_OF_MONTH, week);
c.set(Calendar.DAY_OF_WEEK, day);
return c.getTime();
}
How can I get if the first week of the month have the specific day of the week?

If you use Java 8 or later, it is as simple as:
LocalDate.now()
.plusMonths(1)
.with(TemporalAdjusters.firstInMonth(DayOfWeek.TUESDAY))
.plusWeeks(3);

tl;dr
LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) // Get current date in this particular time zone.
.plusMonths( 1 ) // Move to equivalent date in the month after.
.with(
TemporalAdjusters.dayOfWeekInMonth​( 3 , DayOfWeek.TUESDAY ) // Move to the ordinal number occurrence of a day-of-week within this month.
)
Details
You seem to be asking for the third Tuesday of next month.
The Answer by Mellgren is good, but here's a variation on that idea using a more appropriate TemporalAdjuster.
Avoid legacy classes
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time 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.
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 );
Move to the next month.
LocalDate monthLater = today.plusMonths( 1 );
TemporalAdjuster
To move to the third Tuesday of the month, use an implementation of TemporalAdjuster found in the TemporalAdjusters class.
For an ordinal day-of-week within a month like “Third Tuesday of the month” or “First Thursday of the month”, Java offers a specific adjuster: TemporalAdjusters.dayOfWeekInMonth. Pass the ordinal number such as 3 for “third”, and a DayOfWeek enum object constant such as DayOfWeek.TUESDAY.
TemporalAdjuster ta = TemporalAdjusters.dayOfWeekInMonth( 3 , DayOfWeek.TUESDAY ); // Pass ordinal number and `DayOfWeek`.
LocalDate thirdTuesdayOfNextMonth = monthLater.with( ta );
Dump to console.
System.out.println( "today is " + today + " in zone " + z );
System.out.println( "Third Tuesday of next month is " + thirdTuesdayOfNextMonth );
See this code run live at IdeOne.com.
Today is 2018-01-20 in zone America/Montreal
Third Tuesday of next month is 2018-02-20
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.

Related

Java: Invalid week of year accepted

I have written the following Java code to get a the first day of a week of year.
Calendar cal = Calendar.getInstance(Locale.GERMAN);
cal.clear();
cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, Calendar.MONDAY);
cal.set(Calendar.YEAR, 2016);
cal.set(Calendar.WEEK_OF_YEAR, weekNumber);
DateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
System.out.println( sdf.format(cal.getTime()) );
By using the input week of year 53 it should result into an error acutally because this week of year does not exist in 2016. Instead it shows me the next possible first date from next year.
Is there a neat way to correct my code or do I have to check the input week of year by myself?
Thanks for your help.
tl;dr
If you mean a standard ISO 8601 week, use the YearWeek class from the ThreeTen-Extra library.
For specific week number in specific week-based year:
YearWeek.of( // Standard ISO 8601 week, where week # 1 has the first Thursday of the calendar year, and runs Monday-Sunday.
2018 , // Week-based year, NOT calendar year.
37 // Week-of-week-based-year. Runs 1-52 or 1-53.
)
.atDay( DayOfWeek.MONDAY ) // Returns a `LocalDate` object.
➡ Trap for java.time.DateTimeException if the input is not valid, if there is no such week in that week-based-year.
For current week:
YearWeek.now( // Standard ISO 8601 week, where week # 1 has the first Thursday of the calendar year, and runs Monday-Sunday.
ZoneId.of( "Pacific/Auckland" ) // Determining a week means determining a date, and that requires a time zone. For any given moment, the date varies around the globe by zone.
)
.atDay( DayOfWeek.MONDAY ) // Returns a `LocalDate` object.
Define “week”
Define what you mean by “week”. Is week # 1 the one with January 1st? Is week # 1 the first to have all seven days composed of days in the new year? If so, what is the first-last days of the week, Sunday-Saturday or Monday-Sunday or something else? Or is week # 1 the first to have a certain day of the week?
The troublesome old date-time classes defined a week by depending on Locale. If you fail to specify a Locale, the JVM’s current default Locale is silently implicitly applied. So your results can vary at runtime.
If possible I recommend using the standard ISO 8601 week definition. The week runs from Monday-Sunday, and week # 1 contains the first Thursday of the calendar year. So there are either 52 or 53 weeks per year.
Getting the current week means getting the current date. 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.
If you simply want a certain day-of-week on or before that date, then never mind about the week. Use a TemporalAdjuster implementation found in TemporalAjdusters. Specify your day-of-week via the DayOfWeek enum.
LocalDate mondayOnOrBeforeToday = today.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) ) ;
ThreeTen-Extra library
If you do want to work with ISO 8601 weeks, there is limited support available in the IsoFields class. But I recommend instead that you add the ThreeTen-Extra library to your project. That library provides additional date-time classes that complement those built into Java SE 8 and later. In particular, you get the YearWeek class.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
YearWeek yw = YearWeek.now( z ) ;
Ask for the LocalDate of a day-of-week in that week.
LocalDate ld = yw.atDay( 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.
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.

get month of year from Calendar class of java

I wrote simple java program in which I get day of month, days in month and month
see below code :
//Calendar calendar = Calendar.getInstance();
Calendar calendar = new GregorianCalendar();
log.info("day of month: "+calendar.get(Calendar.DAY_OF_MONTH));
calendar.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH);
log.info("days in month: "+calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
log.info("month: "+calendar.get(Calendar.MONTH));
Running above code I get this output:
day of month: 7
days in month: 31
month: 2
But when I put below statement
log.info("month: "+calendar.get(Calendar.MONTH));
before
log.info("day of month: "+calendar.get(Calendar.DAY_OF_MONTH));
I get this output: (which is what I want)
day of month: 7
days in month: 31
month: 5
Can any body help me understand why I get month: 2 ?
Youre setting the Calendar field to Calendar.MONTH (value 2) here
calendar.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH);
^
You can do this
calendar.set(2014, Calendar.JUNE, 1);
although the Month 5 is June (since month field starts from 0 for Calendar) which only has 30 days
Look at the source code of Calendar.java of JDK.
public final static int MONTH = 2;
Here, Calendar.MONTH = 2, Calendar.YEAR=1 and Calendar.DAY_OF_MONTH = 5. You set these constant value to calender using set method like.
calendar.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH);
| | |
1 2 5
tl;dr
LocalDate.now()
.getDayOfMonth()
…and…
YearMonth.from(
LocalDate.now()
).lengthOfMonth() // .getMonthValue() .getYear()
java.time
The modern approach uses the industry-leading java.time 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.
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 ) ;
Parts
Interrogate for the parts as needed.
int dayOfMonth = ld.getDayOfMonth() ;
int month = ld.getMonthValue() ;
int year = ld.getYear() ;
YearMonth
To work with the month as a whole, use YearMonth class.
YearMonth ym = YearMonth.from( ld ) ;
Ask for length of month.
int lengthOfMonth = ym.lengthOfMonth() ;
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.

Last week date from Date()

AIM: I would like to get the last day of the week (Sunday) for the next 12 weeks into seperate Strings using Date()
I have the below which gives me the correct date format. I just need suggestions on the best solution to achieve my goal.
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date(0);
System.out.println(dateFormat.format(date));
Java's date system baffles me, but I think you want to do this:
1) Instead of making a Date, make a GregorianCalendar.
2) Calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY) to get the date for the sunday of this week.
3) In a for loop, add 7 days to the calendar twelve times. Do something on each loop (For instance, use getTime() to get a Date from the GregorianCalendar)
try
GregorianCalendar c = new GregorianCalendar();
for (int i = 0; i < 12;) {
c.add(Calendar.DATE, 1);
if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
System.out.println(DateFormat.getDateInstance().format(c.getTime()));
i++;
}
}
Firstly, the last of the week is not always the same as Sunday since it is depending on which Locale you are using.
If you are using Java 8, the solution is pretty straightforward:
LocalDate firstJanuary = LocalDate.parse("01/01/2015",
DateTimeFormatter.ofPattern("MM/dd/yyyy"));
//last day of the week
TemporalField fieldUS = WeekFields.of(Locale.US).dayOfWeek();
LocalDate lastDayOfWeek = firstJanuary.with(fieldUS,7);
System.out.println(lastDayOfWeek);
//sunday
LocalDate sunday = firstJanuary.with(DayOfWeek.SUNDAY);
System.out.println(sunday);
and to iterate to the weeks after, simply use:
sunday.plusWeeks(1);
tl;dr
LocalDate.now(
ZoneId.of( "Africa/Tunis" )
)
.withNextOrSame( DayOfWeek.SUNDAY )
.plusWeeks( 1 )
java.time
The modern approach uses the java.time classes.
Today
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.
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 pseudo-zones such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate today = LocalDate.now( z );
Day of week
To find the next Sunday on or after today, use a TemporalAdjuster implementation found in the TemporalAdjusters class.
LocalDate nextOrSameSunday = today.withNextOrSame( DayOfWeek.SUNDAY ) ;
Collection
Collect a dozen such sequential dates.
int countWeeks = 12 ;
List< LocalDate > sundays = new ArrayList<>( 12 ) ;
for( int i = 0 , i < countWeeks , i ++ ) {
sundays.add( nextOrSameSunday.plusWeeks( i ) ) ; // + 0, + 1, + 2, … , + 11.
}
Tip: Focus on working with representative data objects rather than mere Strings. When needed for display, loop your collection and generate strings with a call to toString or format( DateTimeFormatter ).
for( LocalDate ld : sundays ) { // Loop each LocalDate in collection.
String output = ld.toString() ; // Generate a string in standard ISO 8601 format.
…
}
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.

How to display date of a current month with the month and year in Java?

How to display the date, month, and year of a particular month in for loop dynamically in Java?
This demonstrates briefly some of the basics of the SimpleDateFormat and GregorianCalendar classes in Java. It was the best I could do based on your question.
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
public class Main {
public static void main(String[] args) {
int year = 2012;
int month = 4;
/* The format string for how the dates will be printed. */
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
/* Create a calendar for the first of the month. */
GregorianCalendar calendar = new GregorianCalendar(year, month, 1);
/* Loop through the entire month, day by day. */
while (calendar.get(GregorianCalendar.MONTH) == month) {
String dateString = format.format(calendar.getTime());
System.out.println(dateString);
calendar.add(GregorianCalendar.DATE, 1);
}
}
}
Using java.time
The other Answer uses the troublesome old date-time classes, now legacy, supplanted by the java.time classes.
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.
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 );
YearMonth
We care about the whole month. So use a YearMonth object to represent that.
YearMonth ym = YearMonth.from( today );
Get the first of the month.
LocalDate localDate = ym.atDay( 1 );
Loop, incrementing the date by one day at a time, until past the end of month. We can test that fact by seeing if each incremented date has the same YearMonth as today. Collect each date in a List.
List<LocalDate> dates = new ArrayList<>( 31 ); // Collect each date. We know 31 is maximum number of days in any month, so set initial capacity.
while( YearMonth.of( localDate).equals( ym ) ) { // While in the same year-month.
dates.add( localDate ); // Collect each incremented `LocalDate`.
System.out.println( localDate );
// Set up next loop.
localDate = localDate.plusDays( 1 );
}
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 and 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 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.

Date earlier than a month ago

How to check whether the given date is earlier than a month ago? What is the fastest algorithm? I have to take into account that different months have different numbers of days.
Updated to Java 8
The class LocalDate class can be used:
LocalDate aDate = LocalDate.parse("2017-01-01");
return aDate.isBefore( LocalDate.now().minusMonths(1));
For previous versions, the Calendar class would work.
Calendar calendar = Calendar.getInstance();
calendar.add( Calendar.MONTH , -1 );
return aDate.compareTo( calendar.getTime() ) < 0;
Sample code:
import static java.lang.System.out;
import java.time.LocalDate;
public class Sample {
public static void main( String [] args ) {
LocalDate aMonthAgo = LocalDate.now().minusMonths(1);
out.println( LocalDate.parse("2009-12-16").isBefore(aMonthAgo));
out.println( LocalDate.now().isBefore(aMonthAgo));
out.println( LocalDate.parse("2017-12-24").isBefore(aMonthAgo));
}
}
Prints
true
false
false
Using Joda Time:
DateTime dt1 = new DateTime(); //Now
DateTime dt2 = new DateTime(2009,9,1,0,0,0,0); //Other date
if (dt1.plusMonths(-1) > dt2) {
//Date is earlier than a month ago
}
tl;dr
LocalDate.now( ZoneId.of( "America/Montreal" )
.minusMonths( 1 )
.isAfter( LocalDate.parse( "2017-01-23" ) )
java.time
The modern approach uses the java.time classes rather than the troublesome legacy classes such as Date & Calendar.
Today
First get the current date. 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.
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 );
Calculating month-ago
Next, determine the date a month ago.
LocalDate monthAgo = today.minusMonths( 1 ) ;
Here are the rules used by LocalDate::minusMonths, quoted from Java 8 class doc:
This method subtracts the specified amount from the months field in three steps:
Subtract the input months from the month-of-year field
Check if the resulting date would be invalid
Adjust the day-of-month to the last valid day if necessary
For example, 2007-03-31 minus one month would result in the invalid date 2007-02-31. Instead of returning an invalid result, the last valid day of the month, 2007-02-28, is selected instead.
Or, perhaps in your business rules you meant "30 days" instead of a calendar month.
LocalDate thirtyDaysAgo = today.minusDays( 30 ) ;
Input
You are given a date. That should be passed to your code as a LocalDate object.
LocalDate ld = LocalDate.of( 2017 , Month.JANUARY , 23 ) ;
If coming from a String, use the standard ISO 8601 formats. For other formats, search Stack Overflow for DateTimeFormatter class.
LocalDate ld = LocalDate.parse( "2017-01-23" ) ;
Comparison
Now compare. Call the isBefore, isEqual, isAfter methods.
Boolean outdated = ld.isBefore( monthAgo ) ;
Performance
As for the issue of performance raised in the Question: Don't worry about it. This month-ago calculation and comparison is very unlikely to be a bottleneck in your app. Avoid premature optimization.
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.

Categories

Resources