Date and calendar java - java

class Employee
{
private Date doj;
public Employee (Date doj)
{
this.doj=doj;
}
public Date getDoj()
{
return doj;
}
}
class TestEmployeeSort
{
public static List<Employee> getEmployees()
{
List<Employee> col=new ArrayList<Employee>();
col.add(new Employee(new Date(1986,21,22));
}
}
In the above code i have used Date to set a date. I want to know how to use calendar function to do this. I know that i can use getInstance() and set the date. But I don't know how to implement it. Please help me to know how to set Date using Calendar function

tl;dr
LocalDate.of( 1986 , Month.FEBRUARY , 23 )
Date-only
Neither of those classes, Date & Calendar, are suitable.
You apparently want a date-only value without a time-of-day and without a time zone. In contrast, the Date class is a date with a time-of-day in UTC, and Calendar is a date-time with a time zone.
Furthermore, both Date & Calendar are obsolete, replaced by the java.time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
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.
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 ); // Get current date for a particular time zone.
Specific date
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December, unlike the crazy zero-based numbering in the legacy class.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Both year and month have same numbering. 1986 is the year 1986. 1-12 is 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 ) ;
Strings
Generate a String representing the date value in standard ISO 8601 format by calling toString: YYYY-MM-DD. For other formats, see DateTimeFormatter class.
String output = ld.toString() ; // Generate a string in standard ISO 8601 format, YYYY-MM-DD.
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.

String months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec" };
Calendar calendar = Calendar.getInstance();
System.out.print("Date: ");
System.out.print(months[calendar.get(Calendar.MONTH)]);
System.out.print(" " + calendar.get(Calendar.DATE) + " ");
System.out.println(calendar.get(Calendar.YEAR));
System.out.print("Time: ");
System.out.print(calendar.get(Calendar.HOUR) + ":");
System.out.print(calendar.get(Calendar.MINUTE) + ":");
System.out.println(calendar.get(Calendar.SECOND));
calendar.set(Calendar.HOUR, 10);
calendar.set(Calendar.MINUTE, 29);
calendar.set(Calendar.SECOND, 22);
System.out.print("Updated time: ");
System.out.print(calendar.get(Calendar.HOUR) + ":");
System.out.print(calendar.get(Calendar.MINUTE) + ":");
System.out.println(calendar.get(Calendar.SECOND));

Related

Java Calendar get Xº day of the week of month

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.

How to get the date in java by setting DAY_OF_WEEK AND WEEK_OF_MONTH to calender class

i want to get the date after modifying the day of the week using Calender class in java
i want to print 16 7 2015(DD/MM/YYYY);
int monthIndex=6,weekIndex=2,dayIndex=4;
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, (monthIndex + 1));
c.set(Calendar.WEEK_OF_MONTH, weekIndex+1 );
c.set(Calendar.DAY_OF_WEEK, dayIndex+1);
int recurMonth = c.get(Calendar.MONTH);
int recWeek=c.get(Calendar.WEEK_OF_MONTH);
int recurDate = c.get(Calendar.DATE);
int recurYear = c.get(Calendar.YEAR);
int dayofMonth=c.get(Calendar.DAY_OF_MONTH);
int dayofWeek=c.get(Calendar.DAY_OF_WEEK);
int dayofweekinmonth=c.get(Calendar.DAY_OF_WEEK_IN_MONTH);
but its showing wrong date
Its pretty clear, I guess.
Calendar today = Calendar.getInstance();
today.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
today.set(Calendar.WEEK_OF_MONTH, 5);
System.out.println(today.get(Calendar.DATE));
The code is self explanatory.
Format date using SimpleDateFormat:
public void printDate(int weekOfMonth, int dayOFWeek) {
Calendar calendar = Calendar.getInstance(Locale.US);
calendar.set(Calendar.WEEK_OF_MONTH, weekOfMonth);
calendar.set(Calendar.DAY_OF_WEEK, dayOFWeek);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(df.format(calendar.getTime()));
}
tl;dr
To move to the following Monday:
LocalDate.of( 1986 , 2 , 23 ) // Represent a certain date, without time-of-day and without time zone.
.with( TemporalAdjusters.next( DayOfWeek.MONDAY ) ) // Move to the following Monday.
.format( // Generate a string representing this object’s value, using an automatically localizing formatter.
DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( Locale.UK )
)
…or, for "third Monday in the same month":
LocalDate.of( 1986 , 2 , 23 ) // Represent a certain date, without time-of-day and without time zone.
.with( TemporalAdjusters.dayOfWeekInMonth( 3 , DayOfWeek.MONDAY ) ) // Move to the third Monday of the same month.
.format( // Generate a string representing this object’s value, using an automatically localizing formatter.
DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( Locale.UK )
)
java.time
The modern approach uses the java.time classes that supplanted the troublesome old legacy date-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, 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 ) ;
Adjusters
To move to another date, use a TemporalAdjuster implementation found in the TemporalAdjusters class. Specify the desired day-of-week using a DayOfWeek enum object.
LocalDate nextMonday = ld.with( TemporalAdjusters.next( DayOfWeek.MONDAY ) ) ;
If your goal is something like "move to the third Monday of the month", use another TemporalAdjuster implementation.
TemporalAdjuster ta = TemporalAdjusters.dayOfWeekInMonth( 3 , DayOfWeek.MONDAY ) ;
LocalDate thirdMondayOfSameMonth = 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.
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or 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, 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