I am trying to check if a particular date is one week before from today's date. I formatted my date into this format:
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
Then, I get the list of date from a for loop by these code:
Date formattedToday = formatter.parse(todayStr);
Date formattedExpired = formatter.parse(expiredDate);
The example of dates in the list are:
09/12/2017 08:09 PM
10/24/2015 02:09 AM
07/18/2018 03:10 AM
I tried to follow this thread but I am not allowed to add in any external libraries.
The other solution that requires Java 8
is not applicable for me also as my current min API is 25 but ChronoUnit
requires API 26
.
Any ideas? Thanks!
Using only Date
and Calendar
classes (and thus, compatible with any JVM from about 4-ish, I think?) you could try this sort of solution:
Date
: Date now = new Date()
Calendar
: Calendar expected = Calendar.getInstance(); expected.setTime(now); lastWeek.add(Calendar.WEEK_OF_YEAR, -1);
Calendar expected = Calendar.getInstance(); expected.setTime(now); lastWeek.add(Calendar.WEEK_OF_YEAR, -1);
Calendar
: Calendar actual = Calendar.getInstance().setTime(expiredDate);
return (expected.get(Calendar.YEAR) == actual.get(Calendar.YEAR)) && (expected.get(Calendar.WEEK_OF_YEAR) == actual.get(Calendar.WEEK_OF_YEAR));
Using this, you should be able to come up with an even shorter snippet that subtracts a week from now and compares the long values of the two. Though obviously that wouldn't be comparing calendar dates, it would be comparing nanoseconds :)
Here is a complete solution:
import java.util.Calendar;
import java.util.Date;
/**
* @author Jeremi Grenier-Berthiaume
*/
public class InternalDate {
private int year = 0;
private int month = 0;
private int day = 0;
private InternalDate(int year, int month, int day){
this.year = year;
this.month = month;
this.day = day;
}
private static InternalDate generateFromCalendar(Calendar calendar) {
int lYear = calendar.get(Calendar.YEAR);
int lMonth = calendar.get(Calendar.MONTH) + 1; // January = 1st month
int lDay = calendar.get(Calendar.DAY_OF_MONTH);
return new InternalDate(lYear, lMonth, lDay);
}
/**
* Constructor for a textual format.
*
* @param text Format "DD/MM/YYYY" followed by more chars which will be ignored if they are present.
* @return Associated InternalDate
*/
private static InternalDate generateDateFromText(String text) {
int year, month, day;
char selectedChar = '/';
text = text.substring(0,10); // to remove hours
// Extract the data required to construct the InternalDate
String[] splitDateText = text.split(""+selectedChar);
day = Integer.parseInt(splitDateText[0]);
month = Integer.parseInt(splitDateText[1]);
year = Integer.parseInt(splitDateText[2]);
return new InternalDate(year, month, day);
}
private static InternalDate getLastWeek() {
// Get current date
Calendar tempCal = Calendar.getInstance();
tempCal.setTime(new Date());
// 7 days ago
tempCal.add(Calendar.DAY_OF_MONTH, -7);
return generateFromCalendar(tempCal);
}
public static boolean isLastWeek(String compared) {
int tmpDate = Integer.parseInt(InternalDate.getLastWeek().getComparableStringDate());
int tmpCompDate = Integer.parseInt(InternalDate.generateDateFromText(compared).getComparableStringDate());
return tmpDate == tmpCompDate;
}
}
Forming the date that you want to verify as a string of the format DD/MM/YYYY
and giving it in input to InternalDate.isLastWeek(stringDate);
will give you an answer (it returns a boolean: true
if it's a date from a week ago, false
if not).
A nice and simple one-liner that you can call from anywhere in your app. Feel free to mark as an answer if it did respond to your question properly. :)
ZonedDateTime
.now() // Captures current moment as seen by the wall-clock time of the JVM’s current default time zone. Better to pass the optional `ZoneId` argument to specify explicitly the desired/expected time zone.
.minusWeeks( 1 )
.isAfter(
LocalDateTime
.parse(
"09/12/2017 08:09 PM" ,
DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm a" , Locale.US )
)
.atZone(
ZoneId.systemDefault() // Better to pass explicitly the time zone known to have been intended for this input. See discussion below.
)
)
The modern solution uses the java.time classes. Much easier to work with that the terrible old legacy Date
, Calendar
, etc.
Check if date is one week before from today Java
Did you intend to work with just the dates, and ignore the time-of-day? I will assume not, as your inputs have a time-of-day.
Get current moment in UTC.
Instant instant = Instant.now() ; // Current moment in UTC.
Adjust into the time zone implied as the context for you date-time input strings. Apply a ZoneId
to get a ZonedDateTime
object.
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( "Africa/Tunis" ) ; // Replace with the zone you know to have been intended for the input strings.
ZonedDateTime zdtNow = instant.atZone( z ) ; // Adjust from UTC to a time zone.
Subtract a week, a requirement you stated in the Question.
ZonedDateTime zdtWeekAgo = zdtNow.minusWeeks( 1 ) ; // Accounts for anomalies such as Daylight Saving Time (DST).
Parse your input strings as LocalDateTime
objects because they lack any indicator of time zone or offset-from-UTC.
Tips: If at all possible, change those inputs to include their time zone. And change their formats to use the standard ISO 8601 formats rather than custom format.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm a" , Locale.US ) ;
LocalDateTime ldt = LocalDateTime.parse( "09/12/2017 08:09 PM" , f ) ;
Assign the time zone you know to have been intended for those input strings.
ZonedDateTime zdt = ldt.atZone( z ) ;
Compare.
boolean moreThanWeekOld = zdt.isBefore( zdtWeekAgo ) ;
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 8 independent
How about doing it in simple way ie get time from two dates and find the difference
. Convert this difference
into days
to get difference between two dates in days
. Below is working code :
Date formattedToday = new Date();
Date formattedExpired = new Date("06/12/2018 08:09 PM");
int diffInDays = (int)( (formattedToday.getTime() - formattedExpired.getTime())
/ (1000 * 60 * 60 * 24) );
if (diffInDays > 7)
Log.i("Expiration Status : ", "Expired");
It will give you difference between two dates in days
and it can be negative
if expiry date is of future and positive
if expiry date is of past.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.