tl;dr
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.
)
)
Using java.time
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 ) ;
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?