I am using Joda Time 2.1 library.
I have written a method to compare if a given date is between a date range of not. I want it to be inclusive to the start date and end date.I have used LocalDate as I don't want to consider the time part only date part.
Below is the code for it.
isDateBetweenRange(LocalDate start,LocalDate end,LocalDate target){
System.out.println("Start Date : "
+start.toDateTimeAtStartOfDay(DateTimeZone.forID("EST"));
System.out.println("Target Date : "
+targettoDateTimeAtStartOfDay(DateTimeZone.forID("EST"));
System.out.println("End Date : "
+end.toDateTimeAtStartOfDay(DateTimeZone.forID("EST"));
System.out.println(target.isAfter(start));
System.out.println(target.isBefore(end));
}
The output of above method is :
Start Date: 2012-11-20T00:00:00.000-05:00
Target Date: 2012-11-20T00:00:00.000-05:00
End Date : 2012-11-21T00:00:00.000-05:00
target.isAfter(start) : false
target.isBefore(end) : true
My problem is target.isAfter(start) is false even if the target date and start are having the same values.
I want that target >= start but here it considers only target > start.
I want it inclusive.
Does it mean that isAfter method finds a match exclusively ?
I have gone through the javadoc for Joda Time, but didn't found anything about it.
Yes, isAfter is exclusive, otherwise it should probably have been named isEqualOrAfter or something similar.
Solution: Use "not before" instead of "after", and "not after" instead of "before".
boolean isBetweenInclusive(LocalDate start, LocalDate end, LocalDate target) {
return !target.isBefore(start) && !target.isAfter(end);
}
tl;dr
Joda-Time has been supplanted by the java.time classes and the ThreeTen-Extra project.
The LocalDateRange and Interval classes representing a span-of-time use the Half-Open definition. So, asking if the beginning is contained returns true.
LocalDateRange.of( // `org.threeten.extra.LocalDateRange` class represents a pair of `LocalDate` objects as a date range.
LocalDate.of( 2018, 8 , 2 ) , // `java.time.LocalDate` class represents a date-only value, without time-of-day and without time zone.
LocalDate.of( 2018 , 8 , 20 )
) // Returns a `LocalDateRange` object.
.contains(
LocalDate.now() // Capture the current date as seen in the wall-clock time used by the people of the JVM’s current default time zone.
)
true
java.time
FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.
Date-only
Apparently you may care about the date and not the time-of-day. If so, use LocalDate class.
For managing a date range, add the ThreeTen-Extra library to your project. This gives you access to the LocalDateRange class.
That class offers several methods for comparison: abuts, contains, encloses, equals, intersection, isBefore, isAfter, isConnected, overlaps, span, and union.
LocalDateRange r =
LocalDateRange.of(
LocalDate.of( 2018, 8 , 2 ) ,
LocalDate.of( 2018 , 8 , 20 )
)
;
LocalDate target = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ; // Capture the current date as seen in the wall-clock time used by the people of a particular time zone.
boolean contains = r.contains( target ) ;
Date-time
If you care about the date and the time-of-day in a particular time zone, use ZonedDateTime class.
Start with your LocalDate, and let that class determine the first moment of the day. The day does not always start at 00:00:00 because of anomalies such as Daylight Saving Time (DST).
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" ) ; // Or "America/New_York", etc.
ZonedDateTime zdtStart = LocalDate.of( 2018, 8 , 2 ).atStartOfDay( z ) ;
ZonedDateTime zdtStop = LocalDate.of( 2018, 8 , 20 ).atStartOfDay( z ) ;
ZonedDateTime zdtTarget = ZonedDateTime.now( z ) ;
Represent a range with the Interval from ThreeTen-Extra. This class represents a pair of Instant objects. An Instant is a moment in UTC, always in UTC. We can easily adjust from our zoned moment to UTC by simply extracting an Instant. Same moment, same point on the timeline, different wall-clock time.
Instant instantStart = zdtStart.toInstant() ;
Instant instantStop = zdtStop.toInstant() ;
Instant instantTarget = zdtTarget.toInstant() ;
Interval interval = Interval.of( instantStart , intervalStop ) ;
boolean contains = interval.contains( instantTarget ) ;
Half-Open
The best approach to defining a span-of-time is generally the Half-Open approach. This means the beginning is inclusive while the ending is exclusive.
The comparisons in the ThreeTen-Extra range classes seen above (LocalDateRange & Interval) both use Half-Open approach. So asking if the starting date or starting moment is contained in the range results in a true.
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.
Related
I have a timestamp in epoch milliseconds and I want to check if it is between two LocalDateTime stamps. What's the best way to do this in java?
One way to do it is to convert the milliseconds to LocalDateTime
LocalDateTime date = Instant.ofEpochMilli(milliseconds)
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
LocalDateTime start = LocalDateTime.now().minusMinutes(1);
LocalDateTime end = LocalDateTime.now().plusMinutes(1);
if (date.isAfter(start) && date.isBefore(end)) {
// date is between start and end
}
tl;dr
You cannot compare a LocalDateTime to a moment until assigning a time zone (or offset-from-UTC).
org.threeten.extra.Interval // Represents a span-of-time attached to the timeline, as a pair of `Instant` objects, a pair of moments in UTC.
.of (
myLocalDateTimeStart
.atZone( ZoneId.of( "Pacific/Auckland" ) ) // Determine a moment by assigning an time zone to a `LocalDateTime` to produce a `ZonedDateTime`, from which we extract an `Instant` to adjust into UTC.
.toInstant() ,
myLocalDateTimeStop
.atZone( ZoneId.of( "Pacific/Auckland" ) ) // Returns a `ZonedDateTime` object.
.toInstant() // From the `ZonedDateTime`, extract a `Instant` object.
) // Returns `Interval` object.
.contains(
Instant.ofEpochMilli( 1_532_463_173_752L ) // Parse a count of milliseconds since 1970-01-01T00:00:00Z as a moment in UTC, a `Instant` object.
) // Returns a boolean.
Details
Comparing time in java between epoch milliseconds and LocalDateTime
You cannot. That comparison is illogical.
A LocalDateTime does not represent a moment, is not a point on the timeline. A LocalDateTime represents potential moments along a range of about 26-27 hours, the range of time zones around the world.
As such it has no real meaning until you place it in the context of a time zone. If that particular date and time were invalid in that zone, such as during a Daylight Saving Time (DST) cut-over, or during some other such anomaly, the ZonedDateTime class adjusts.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = myLocalDateTime.atZone( z ) ;
For comparisons, we will adjust into UTC by extracting an Instant object from your start and stop ZonedDateTime objects.
Instant start = zdtStart.toInstant() ;
Instant stop = zdtStop.toInstant() ;
Now parse your count of milliseconds since the epoch reference of first moment of 1970 as a Instant. Instant has an even finer resolution, nanoseconds.
Instant instant = Instant.ofEpochMilli( 1_532_463_173_752L ) ;
Compare to see if your epoch-milliseconds represent a moment in between our stop and start Instant objects. Usually in date-time work, the Half-Open approach is best, where the beginning is inclusive while the ending is exclusive.
Tip: A shorter way of saying “is equal to or is after” is to say “is not before”.
boolean inRange = ( ! instant.isBefore( start ) ) && instant.isBefore( stop ) ;
To make this work easier, add the ThreeTen-Extra library to your project. Use the Interval class.
Interval interval = Interval.of( start , stop ) ;
boolean inRange = interval.contains( instant ) ; // Uses Half-Open approach to comparisons.
Tip: If you had intended to be tracking moments, you should not have been using LocalDateTime class at all. Instead, use the Instant, OffsetDateTime, and ZonedDateTime classes.
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.
When comparing an Instant (time-since-Epoch) with a LocalDateTime, you always need to consider the timezone of the local times. Here's an example:
Instant now = Instant.now();
LocalDateTime start = LocalDateTime.of(2018, 7, 24, 0, 0);
LocalDateTime end = LocalDateTime.of(2018, 7, 24, 23, 59);
final ZoneId myLocalZone = ZoneId.of("Europe/Paris");
if (now.isAfter(start.atZone(myLocalZone).toInstant())
&& now.isBefore(end.atZone(myLocalZone).toInstant())) {
// the instant is between the local date-times
}
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.
I am trying to get a list of dates in scala
val savePoint:java.util.Date= //olderDate
var days = List[String]()
for (date<-savePoint to java.util.Date.parse("yyyy-MM-dd") by date.plusDays(1)){
days::=date
}
but getting error
value to is not a member of java.util.Date
tl;dr
Using java.time.LocalDate, produce a stream by calling datesUntil, collected into a List.
In Java syntax (I don't know Scala):
LocalDate // Represent a date-only value, without time-of-day, and without offset-from-UTC or time zone.
.of( 2019 , Month.SEPTEMBER , 22 ) // Specify you date in the past.
.dateUntil( // Generate a Stream of LocalDate objects.
LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) // Capture the current date as seen through the wall-clock time used by the people of a particular region (a time zone).
) // Returns a `Stream< LocalDate >`.
.collect ( // Collects the items provided by the stream.
Collectors.toUnmodifiableList () // Instantiates an unmodifiable `List` of some indeterminate concrete class.
) // Returns a `List` holding `LocalDate` objects.
.toString() // Generates a textual listing of the collected dates using standard ISO 8601 format.
[2019-09-22, 2019-09-23, 2019-09-24, 2019-09-25, 2019-09-26, 2019-09-27, 2019-09-28, 2019-09-29, 2019-09-30, 2019-10-01, 2019-10-02, 2019-10-03]
java.time
The modern solution uses the java.time classes, specifically LocalDate.
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 you want to use the JVM’s current default time zone, make your intention clear by calling ZoneId.systemDefault(). 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 ) ;
LocalDate::datesUntil ➙ Stream of LocalDate objects
You can accomplish your goal in a one-liner, by calling LocalDate::datesUntil to generate a stream that can be collected into a list.
ZoneId z = ZoneId.of ( "America/Edmonton" );
LocalDate today = LocalDate.now ( z );
LocalDate then = LocalDate.of ( 2019 , Month.SEPTEMBER , 22 );
List < LocalDate > dates = then.datesUntil ( today ).collect ( Collectors.toUnmodifiableList () );
Dump to console.
System.out.println ( "From: " + then + " to: " + today + " is: " + dates );
From: 2019-09-22 to: 2019-10-04 is: [2019-09-22, 2019-09-23, 2019-09-24, 2019-09-25, 2019-09-26, 2019-09-27, 2019-09-28, 2019-09-29, 2019-09-30, 2019-10-01, 2019-10-02, 2019-10-03]
org.threeten.extra.LocalDateRange
FYI, to represent a span-of-time between a pair of dates, you can use the LocalDateRange class from the ThreeTen-Extra project.
LocalDateRange range = LocalDateRange.of( then , 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.
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.
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.
For Scala, you can use Lamma Date (http://www.lamma.io)
Welcome to Scala version 2.11.6 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_71).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import io.lamma._
import io.lamma._
scala> Date(2015, 7, 1) to Date.today() foreach println
Date(2015,7,1)
Date(2015,7,2)
Date(2015,7,3)
Date(2015,7,4)
Date(2015,7,5)
Date(2015,7,6)
Date(2015,7,7)
I am comparing 2 Calendar objects in java. This the way i am setting each of them
Calendar calendar1 = Calendar.getInstance();
calendar1.set(2012, 6, 17, 13, 0);
And i am getting the following value from table column '2012-07-17 13:00:00' and setting it into Date Java object and then this Date object i am using to set second Calander object.
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(/*Above date object who value is '2012-07-17 13:00:00'*/);
Now when i compare i expect this to be true since both the Calender object are same
calendar2.compareTo(calendar1) >= 0
but instead i am seeing this is becoming true
calendar2.compareTo(calendar1) < 0
Can somebody help?
The following will give you the idea of what's going on (assuming you are parsing the string to produce the date object for calendar1):
Calendar calendar1 = Calendar.getInstance();
calendar1.set(2012, 6, 17, 13, 0);
System.out.println(calendar1.getTime());
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-07-17 13:00:00");
System.out.println(date);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(date);
System.out.println(calendar2.compareTo(calendar1));
calendar1.set(Calendar.SECOND, 0); //setting second to 0
calendar1.set(Calendar.MILLISECOND, 0); //setting millisecond to 0
System.out.println(calendar2.compareTo(calendar1));
Test run result:
Tue Jul 17 13:00:47 CDT 2012
Tue Jul 17 13:00:00 CDT 2012
-1
0
After suggestion from #Bhesh Gurung i used the following
calendar1.set(Calendar.MILLISECOND, 0);
calendar1.set(Calendar.SECOND, 0);
calendar2.set(Calendar.MILLISECOND, 0);
calendar2.set(Calendar.SECOND, 0);
and it worked.
tl;dr
ZonedDateTime.of( // Represent a specific moment using the wall-clock time observed by the people of a specific region (a time zone).
2012 , Month.JULY , 17, 13 , 0 , 0 , 0 , // Hard-code the date and time-of-day, plus zone.
ZoneId.of( "America/Montreal" ) // Specify time zone by Continent/Region name, never by 3-4 letter pseudo-one such as PST or CST.
) // Returns a `ZonedDateTime` object.
.toInstant() // Adjust into UTC.
.equals(
myResultSet.getObject( … , Instant.class ) // Retrieve an `Instant` object for a date-time value stored in your database.
)
Time zone
You do not provide enough info for a definitive answer, but as others suggested you likely are seeing a problem with time zones. Your code does not address this crucial issue explicitly. But, implicitly, your creation of a Calendar item assigns a time zone.
java.time
More importantly, you are using troublesome old date-time classes now supplanted by the java.time classes.
Replace your use use of Calendar with Instant and ZonedDateTime.
For a ZonedDateTime, specify your desired/expected time zone explicitly rather than have the JVM’s current default time zone be applied implicitly. 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" ) ;
ZonedDateTime zdt = ZonedDateTime.of( 2012 , Month.JULY , 17, 13 , 0 , 0 , 0 , z );
Adjust into UTC by extracting a Instant. 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).
Instant instant = zdt.toInstant() ;
Database
From your database, exchange objects rather than mere strings. As of JDBC 4.2 and later, you can exchange java.time objects.
Most databases store a moment such as the SQL-standard type TIMESTAMP WITH TIME ZONE as a value in UTC. So using an Instant object is usually best.
Store your Instant object’s value.
myPreparedStatement.setObject( … , instant ) ;
Retrieval.
Instant instantDb = myResultSet.getObject( … , Instant.class ) ;
Compare using the Instant methods equals, isBefore, and isAfter.
boolean sameMoment = instant.equals( instantDb ) ;
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.
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.