I am searching for a method to get the last third of two dates.
first example:
Date 1 = 22:00
Date 2 = 01:00 (next day)
calculateLastThird(); (output: 00:00)
second example:
Date 1 = 22:25
Date 2 = 01:45 (next day)
calculateLastThird(); (output: 00:38)
I already know how to get the midpoint between those two dates:
Date midpoint = new Date((date1.getTime() + date2.getTime()) / 2);
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work.
ZoneId zone = ZoneId.of("America/Boise");
ZonedDateTime zdt1 = ZonedDateTime.of(2020, 12, 26, 22, 0, 0, 0, zone);
ZonedDateTime zdt2 = ZonedDateTime.of(2020, 12, 27, 1, 0, 0, 0, zone);
Duration fullElapsedTime = Duration.between(zdt1, zdt2);
Duration twoThirds = fullElapsedTime.multipliedBy(2).dividedBy(3);
ZonedDateTime lastThird = zdt1.plus(twoThirds);
System.out.println(lastThird);
Output from this snippet is:
2020-12-27T00:00-07:00[America/Boise]
Three things I like about this code are:
It pretty well mimics the way one would do the calculation by hand and how you would explain to someone else which calculation you want at all.
It takes any transistion to or from summer time (DST) into account.
It leaves the actual calculation to the library methods. It involves no low-level addition or division in your own code.
Link
Oracle tutorial: Date Time explaining how to use java.time.
One way to do this is the following:
Date midpoint = new Date((date1.getTime() + 2 * date2.getTime()) / 3);
If you insist using Date.
It should be a simple math:
First, need to calculate the difference between the two dates (in milliseconds).
Then get the 2/3 rd of that value and add it to the first date.
private static Date calculateLastThird(Date d1, Date d2) {
// Calculate time difference in milliseconds
long differenceMillis = d2.getTime() - d1.getTime();
double millisToAdd = (2.0/3.0) * differenceMillis;
Date twoThird = new Date(d1.getTime() + (long) millisToAdd);
return twoThird;
}
public static void main(String args[]) {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
Date date1= sdf1.parse("2020/12/26 22:00:00");
Date date2= sdf1.parse("2020/12/27 01:00:00");
SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm");
System.out.println("Last third: " + sdf2.format(calculateLastThird(date1, date2)));
Date date3= sdf1.parse("2020/12/26 22:25:00");
Date date4= sdf1.parse("2020/12/27 01:45:00");
System.out.println("Last third: " + sdf2.format(calculateLastThird(date3, date4)));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Sample output of above code:
Last third: 00:00
Last third: 00:38
Related
I googled for a while and the most commonly used method seems to be
date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
However, this method seems to fail for dates before 1893-04-01
The following test fails on my machine with an outcome of 1893-03-31 instead of 1893-04-01:
#Test
public void testBeforeApril1893() throws ParseException {
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("1893-04-01");
System.out.println(date);
LocalDate localDate2 = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println(localDate2);
assertEquals(1893, localDate2.getYear());
assertEquals(4, localDate2.getMonth().getValue());
assertEquals(1, localDate2.getDayOfMonth());
}
The System.out.prinlns are for me to double check the created dates. I see the following output:
Sun Apr 02 00:00:00 CET 1893
1893-04-02
Sat Apr 01 00:00:00 CET 1893
1893-03-31
For 1400-04-01 I even get an output of 1400-04-09.
Is there any method to convert dates before 1893-04 correctly to LocalDate?
As some helpfully pointed out, the reason for this shift is explained in this question. However, I don't see how I can deduce a correct conversion based on this knowledge.
If you're just parsing a String input, it's straighforward:
LocalDate d1 = LocalDate.parse("1893-04-01");
System.out.println(d1); // 1893-04-01
LocalDate d2 = LocalDate.parse("1400-04-01");
System.out.println(d2); // 1400-04-01
The output is:
1893-04-01
1400-04-01
But if you have a java.util.Date object and need to convert it, it's a little bit more complicated.
A java.util.Date contains the number of milliseconds from unix epoch (1970-01-01T00:00Z). So you can say "it's in UTC", but when you print it, the value is "converted" to the system's default timezone (in your case, it's CET). And SimpleDateFormat also uses the default timezone internally (in obscure ways that I must admit I don't fully understand).
In your example, the millis value of -2422054800000 is equivalent to the UTC instant 1893-03-31T23:00:00Z. Checking this value in Europe/Berlin timezone:
System.out.println(Instant.ofEpochMilli(-2422054800000L).atZone(ZoneId.of("Europe/Berlin")));
The output is:
1893-03-31T23:53:28+00:53:28[Europe/Berlin]
Yes, it's very strange, but all places used strange offsets before 1900 - each city had its own local time, before UTC standard took place. That explains why you get 1893-03-31. The Date object prints April 1st probably because the old API (java.util.TimeZone) doesn't have all the offsets history, so it assumes it's +01:00.
One alternative to make this work is to always use UTC as the timezone:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // set UTC to the format
Date date = sdf.parse("1893-04-01");
LocalDate d = date.toInstant().atZone(ZoneOffset.UTC).toLocalDate();
System.out.println(d); // 1893-04-01
This will get the correct local date: 1893-04-01.
But for dates before 1582-10-15, the code above doesn't work. That's the date when the Gregorian Calendar was introduced. Before it, the Julian Calendar was used, and dates before it need an adjustment.
I could do it with the ThreeTen Extra project (an extension of java.time classes, created by the same guy BTW). In the org.threeten.extra.chrono package there are the JulianChronology and JulianDate classes:
// using the same SimpleDateFormat as above (with UTC set)
date = sdf.parse("1400-04-01");
// get julian date from date
JulianDate julianDate = JulianChronology.INSTANCE.date(date.toInstant().atZone(ZoneOffset.UTC));
System.out.println(julianDate); // Julian AD 1400-04-01
The output will be:
Julian AD 1400-04-01
Now we need to convert the JulianDate to a LocalDate. If I do LocalDate.from(julianDate) it converts to Gregorian calendar (and the result is 1400-04-10).
But if you want to create a LocalDate with exactly 1400-04-01, you'll have to do this:
LocalDate converted = LocalDate.of(julianDate.get(ChronoField.YEAR_OF_ERA),
julianDate.get(ChronoField.MONTH_OF_YEAR),
julianDate.get(ChronoField.DAY_OF_MONTH));
System.out.println(converted); // 1400-04-01
The output will be:
1400-04-01
Just be aware that dates before 1582-10-15 have this adjustment and SimpleDateFormat can't handle these cases properly. If you need to work just with 1400-04-01 (year/month/day values), use a LocalDate. But if you need to convert it to a java.util.Date, be aware that it might not be the same date (due to Gregorian/Julian adjustments).
If you don't want to add another dependency, you can also do all the math by hand. I've adapted the code from ThreeTen, but IMO the ideal is to use the API itself (as it can cover corner cases and other things I'm probably missing by just copying a piece of code):
// auxiliary method
public LocalDate ofYearDay(int prolepticYear, int dayOfYear) {
boolean leap = (prolepticYear % 4) == 0;
if (dayOfYear == 366 && leap == false) {
throw new DateTimeException("Invalid date 'DayOfYear 366' as '" + prolepticYear + "' is not a leap year");
}
Month moy = Month.of((dayOfYear - 1) / 31 + 1);
int monthEnd = moy.firstDayOfYear(leap) + moy.length(leap) - 1;
if (dayOfYear > monthEnd) {
moy = moy.plus(1);
}
int dom = dayOfYear - moy.firstDayOfYear(leap) + 1;
return LocalDate.of(prolepticYear, moy.getValue(), dom);
}
// sdf with UTC set, as above
Date date = sdf.parse("1400-04-01");
ZonedDateTime z = date.toInstant().atZone(ZoneOffset.UTC);
LocalDate d;
// difference between the ISO and Julian epoch day count
long julianToIso = 719164;
int daysPerCicle = (365 * 4) + 1;
long julianEpochDay = z.toLocalDate().toEpochDay() + julianToIso;
long cycle = Math.floorDiv(julianEpochDay, daysPerCicle);
long daysInCycle = Math.floorMod(julianEpochDay, daysPerCicle);
if (daysInCycle == daysPerCicle - 1) {
int year = (int) ((cycle * 4 + 3) + 1);
d = ofYearDay(year, 366);
} else {
int year = (int) ((cycle * 4 + daysInCycle / 365) + 1);
int doy = (int) ((daysInCycle % 365) + 1);
d = ofYearDay(year, doy);
}
System.out.println(d); // 1400-04-01
The output will be:
1400-04-01
Just reminding that all this math is not needed for dates after 1582-10-15.
Anyway, if you have an input String and want to parse it, don't use SimpleDateFormat - you can use LocalDate.parse() instead. Or LocalDate.of(year, month, day) if you already know the values.
But converting these local dates from/to a java.util.Date is more complicated, because Date represents the full timestamp millis and dates can vary according to the calendar system in use.
Seems to be a known bug that won't get fixed: https://bugs.openjdk.java.net/browse/JDK-8061577
After a lot of research I gave up with every simple API method and just convert it by hand. You could wrap the date in a sql.Date and call toLocalDate() or you just use the same deprecated methods as sql.Date does.
Without deprecated methods you need to convert your util.Date to Calendar and get the fields one by one:
Calendar calendar = Calendar.getInstance();
calendar.setTime(value);
return LocalDate.of(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1,
calendar.get(Calendar.DAY_OF_MONTH));
If you futher want to have a two digit year conversion like in SimpleDateFormat (convert the date in range of now - 80 years till now + 19 years) you could use this implementation:
Calendar calendar = Calendar.getInstance();
calendar.setTime(value);
int year = calendar.get(Calendar.YEAR);
if (year <= 99) {
LocalDate pivotLocalDate = LocalDate.now().minusYears(80);
int pivotYearOfCentury = pivotLocalDate.getYear() % 100;
int pivotCentury = pivotLocalDate.minusYears(pivotYearOfCentury).getYear();
if (year < pivotYearOfCentury) {
year += 100;
}
year += pivotCentury;
}
return LocalDate.of(year, calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH));
Conclusion: it is realy ugly and I can't believe that there isn't any simple API!
This code works for me:
#Test
public void oldDate() throws ParseException {
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("1893-04-01");
assertEquals("1893-04-01", String.format("%tF", date));
}
I have this problem with calculating time difference in minutes.
Its working fine with exampples like calculating the difference between
2045 and 2300.
But when I want to calculate the difference between for example
2330 (today) and 0245 (tomorrow) I get a incorrect answer.
Code below:
// This example works
String dateStart = "2045";
String dateStop = "2300";
// This example doesnt work
//String dateStart = "2330";
//String dateStop = "0245";
// Custom date format
SimpleDateFormat format = new SimpleDateFormat("HHmm");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
} catch (Exception e) {
e.printStackTrace();
}
long diff = d2.getTime() - d1.getTime();
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
System.out.println("Time in minutes: " + minutes + " minutes.");
Thanks in advance
Consider using LocalDate, LocalDateTime, LocalTime ZonedDateTime classes from java.time.* package introduced in Java 8. They are very handy in use as they can address various corner cases (e.g. measuring minutes across different time zones, or during autumn and spring time change).
The thing to you need to know when you calculate time difference is that:
LocalTime contains time only
LocalDate contains date only (no time)
LocalDateTime contains both (date + time.)
ZonedDateTime contains date + time + timezone
This implies that difference between times will be different when you compare with:
LocalTime you can diff only time so 20:45 and 23:30 gives 2:45 of difference
LocalDate you cannot calculate any time diffs (contains no time)
LocalDateTime you can specify date and time, e.g.: 20:45 on 1Jan and 23:30 on 3Jan . Time difference will be 2:45 and 2 days of difference, or 50:45.
ZonedDateTime - same as LocalDateTime plus you takes into account DayLightSavings, so if the clock is changed overnight - it will get reflected.
Here is a snippet for a LocalDateTime:
LocalDateTime today2045 = LocalDateTime.of(
LocalDate.now(),
LocalTime.parse("20:45"));
LocalDateTime tomorrow0230 = LocalDateTime.of(
LocalDate.now().plusDays(1),
LocalTime.parse("02:30"));
System.out.println("Difference [minutes]: " +
Duration.between(today2045, tomorrow0230).toMinutes());
For ZonedDateTime taking into account spring/autumn clock changes:
ZonedDateTime today2045 = ZonedDateTime.of(
LocalDate.now(),
LocalTime.parse("20:45"),
ZoneId.systemDefault());
ZonedDateTime tomorrow0230 = ZonedDateTime.of(
LocalDate.now().plusDays(1),
LocalTime.parse("02:30"),
ZoneId.systemDefault());
System.out.println("Difference [minutes]: " +
Duration.between(today2045, tomorrow0230).toMinutes());
Some info on constructors can be found in Oracle's tutorial here.
This is not working because when you create a new date with just a time in it, it's assuming the day is "today".
What you could do is:
// This example works
String dateStart = "2045";
String dateStop = "2300";
// This example doesnt work
//String dateStart = "2330";
//String dateStop = "0245";
// Custom date format
SimpleDateFormat format = new SimpleDateFormat("HHmm");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
} catch (Exception e) {
e.printStackTrace();
}
// MY ADDITION TO YOUR CODE STARTS HERE
if(d2.before(d1)){
Calendar c = Calendar.getInstance();
c.setTime(d2);
c.add(Calendar.DATE, 1);
d2 = c.getTime();
}
// ENDS HERE
long diff = d2.getTime() - d1.getTime();
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
System.out.println("Time in minutes: " + minutes + " minutes.");
But you should consider using Java 8 new Date/Time features, or Joda Time.
You can add if statement to check if this is today, and if no you can add one day to this, since you are comparing time it wont be problem if you add full day
if(d2.before(d1)){
d2.setTime(d2.getTime()+86400000);
}
Try it out
This is a solved problem. If you look at the Joda Time library you'll find all the time and date manipulation functions you could possibly want:
In your case something along the lines of:
DateTime first = new DateTime(larger-time);
DateTime second = new DateTime(smaller-time);
DateTime difference = first.minusMillis(second.getMillis())
Joda will cope with all the odd edge conditions like rolling over between days/months/years, lengths of months, leap years, daylight savings, timezones...
This question already has answers here:
Android/Java - Date Difference in days
(18 answers)
Closed 6 years ago.
I need to calculate number of days between two dates and I am using below code. problem is it is returning me 2 but actually it should return 3 because difference between 30 june 2016 to 27 june is 3. can you please help where it should include current date as well in difference?
public static long getNoOfDaysBtwnDates(String expiryDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
long diff = 0;
long noOfDays = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Date createdDate = new Date();
diff = expDate.getTime() - createdDate.getTime();
noOfDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
long a = TimeUnit.DAYS.toDays(noOfDays);
// logger.info("No of Day after difference are - " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
System.out.println(a);
System.out.println(noOfDays);
} catch (ParseException e) {
e.printStackTrace();
}
return noOfDays;
}
expiry date is 2016-06-30 and current date is 2016-06-27
Reason is, you are not subtracting two dates with same time format.
Use Calendar class to change the time as 00:00:00 for both date and you will get exact difference in days.
Date createdDate = new Date();
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 0);
time.set(Calendar.MINUTE, 0);
time.set(Calendar.SECOND, 0);
time.set(Calendar.MILLISECOND, 0);
createdDate = time.getTime();
More explaination in Jim Garrison' answer
Why not use LocalDate?
import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.DAYS;
long diffInDays(LocalDate a, LocalDate b) {
return DAYS.between(a, b);
}
The problem is that
Date createdDate = new Date();
sets createdDate to the current instant, that is, it includes the current time as well as the date. When you parse a string using the given format, the time is initialized to 00:00:00.
Let's say you ran this at exactly 18:00 local time, you end up with
createdDate = 2016-06-27 18:00:00.000
expDate = 2016-06-30 00:00:00.000
The difference is 2 days 6 hours, not 3 days.
You should be using the newer java.time.* classes from Java 8. There is a class LocalDate that represents dates without time-of-day. It includes methods for parsing using a format, and LocalDate.now() to get the current date, as well as methods for calculating intervals between LocalDate instances.
Using the Calendar.get(Calendar.DAY_OF_MONTH) as pointed out by python:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
String expiryDate ="2016-06-30";
int diff = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Calendar cal = Calendar.getInstance();
int today = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(expDate);
diff = cal.get(Calendar.DAY_OF_MONTH)- today;
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(diff);
I want to find out difference in milliseconds between next occuring 3PM new york time and current time. i.e. if it is 5 pm NY time right now. I should get the difference between 5pm now and 3pm NY time next day. How can I do it in Java ? I am happy using JodaTime also, may you please give an exmaple, how this can be done.
Please help.
Here are three solutions using the most prevalent library choices. They all follow the same pattern, just using the nomenclature of the given libraries.
Joda solution:
DateTime dt = new DateTime(DateTimeZone.forID("US/Eastern"));
DateTime target = dt
.withHourOfDay(15)
.withMinuteOfHour(0)
.withSecondOfMinute(0)
.withMillisOfSecond(0);
if (target.isBefore(dt)) {
target = target.plusDays(1);
}
System.out.println(target.getMillis() - dt.getMillis());
Java 8 solution
Got to love that until() method:
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("US/Eastern"));
ZonedDateTime target2 = zdt
.withHour(15)
.withMinute(0)
.withSecond(0)
.withNano(0);
if (target2.isBefore(zdt)) {
zdt = zdt.plusDays(1);
}
System.out.println(zdt.until(target2, ChronoUnit.MILLIS));
Java <=7 solution
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("US/Eastern"));
Calendar target3 = Calendar.getInstance(TimeZone.getTimeZone("US/Eastern"));
target3.set(Calendar.HOUR_OF_DAY, 15);
target3.set(Calendar.MINUTE, 0);
target3.set(Calendar.SECOND, 0);
target3.set(Calendar.MILLISECOND, 0);
if (target3.before(c)) {
target3.add(Calendar.DATE, 1);
}
System.out.println(target3.getTimeInMillis() - c.getTimeInMillis());
How about this?
Date now = new Date();
Calendar ny3pmCalendar = new GregorianCalendar(TimeZone.getTimeZone("America/New_York"));
ny3pmCalendar.setTime(now);
if(ny3pmCalendar.get(Calendar.HOUR_OF_DAY) >= 15) {
// next day
ny3pmCalendar.add(Calendar.DAY_OF_YEAR, 1);
}
ny3pmCalendar.set(Calendar.HOUR, 15);
ny3pmCalendar.set(Calendar.MINUTE, 0);
ny3pmCalendar.set(Calendar.SECOND, 0);
ny3pmCalendar.set(Calendar.MILLISECOND, 0);
long diff = ny3pmCalendar.getTimeInMillis() - now.getTime();
System.out.println(diff);
try joda DateTime and Period
Date oldDate = new Date();
DateTime old = new DateTime(oldDate);
DateTime now = new DateTime();
Period period = new Period(old, now, PeriodType.yearMonthDayTime());
period.getYears();// give the difference in year
period.getMonths();
period.getDays();
period.getMinutes();
period.getSeconds();
Joda Time - Its having lots of features for date time manipulation
This question already has answers here:
How to compare dates in Java? [duplicate]
(11 answers)
Closed 9 years ago.
I have two dates:
toDate (user input in MM/dd/yyyy format)
currentDate (obtained by new Date())
I need to compare the currentDate with toDate. I have to display a report only when the toDate is equal to or more than currentDate. How can I do that?
It is easier to compare dates using the java.util.Calendar.
Here is what you might do:
Calendar toDate = Calendar.getInstance();
Calendar nowDate = Calendar.getInstance();
toDate.set(<set-year>,<set-month>,<set-day>);
if(!toDate.before(nowDate)) {
//display your report
} else {
// don't display the report
}
If you're set on using Java Dates rather than, say, JodaTime, use a java.text.DateFormat to convert the string to a Date, then compare the two using .equals:
I almost forgot: You need to zero out the hours, minutes, seconds, and milliseconds on the current date before comparing them. I used a Calendar object below to do it.
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
// Other code here
String toDate;
//toDate = "05/11/2010";
// Value assigned to toDate somewhere in here
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
Calendar currDtCal = Calendar.getInstance();
// Zero out the hour, minute, second, and millisecond
currDtCal.set(Calendar.HOUR_OF_DAY, 0);
currDtCal.set(Calendar.MINUTE, 0);
currDtCal.set(Calendar.SECOND, 0);
currDtCal.set(Calendar.MILLISECOND, 0);
Date currDt = currDtCal.getTime();
Date toDt;
try {
toDt = df.parse(toDate);
} catch (ParseException e) {
toDt = null;
// Print some error message back to the user
}
if (currDt.equals(toDt)) {
// They're the same date
}
Date#equals() and Date#after()
If there is a possibility that the hour and minute fields are != 0, you'd have to set them to 0.
I can't forget to mention that using java.util.Date is considered a bad practice, and most of its methods are deprecated. Use java.util.Calendar or JodaTime, if possible.
You are probably looking for:
!toDate.before(currentDate)
before() and after() test whether the date is strictly before or after. So you have to take the negation of the other one to get non strict behaviour.
This is one of the ways:
String toDate = "05/11/2010";
if (new SimpleDateFormat("MM/dd/yyyy").parse(toDate).getTime() / (1000 * 60 * 60 * 24) >= System.currentTimeMillis() / (1000 * 60 * 60 * 24)) {
System.out.println("Display report.");
} else {
System.out.println("Don't display report.");
}
A bit more easy interpretable:
String toDateAsString = "05/11/2010";
Date toDate = new SimpleDateFormat("MM/dd/yyyy").parse(toDateAsString);
long toDateAsTimestamp = toDate.getTime();
long currentTimestamp = System.currentTimeMillis();
long getRidOfTime = 1000 * 60 * 60 * 24;
long toDateAsTimestampWithoutTime = toDateAsTimestamp / getRidOfTime;
long currentTimestampWithoutTime = currentTimestamp / getRidOfTime;
if (toDateAsTimestampWithoutTime >= currentTimestampWithoutTime) {
System.out.println("Display report.");
} else {
System.out.println("Don't display report.");
}
Oh, as a bonus, the JodaTime's variant:
String toDateAsString = "05/11/2010";
DateTime toDate = DateTimeFormat.forPattern("MM/dd/yyyy").parseDateTime(toDateAsString);
DateTime now = new DateTime();
if (!toDate.toLocalDate().isBefore(now.toLocalDate())) {
System.out.println("Display report.");
} else {
System.out.println("Don't display report.");
}
Date long getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
//test if date1 is before date2
if(date1.getTime() < date2.getTime()) {
....
}
private boolean checkDateLimit() {
long CurrentDateInMilisecond = System.currentTimeMillis(); // Date 1
long Date1InMilisecond = Date1.getTimeInMillis(); //Date2
if (CurrentDateInMilisecond <= Date1InMilisecond) {
return true;
} else {
return false;
}
}
// Convert both date into milisecond value .
If for some reason you're intent on using Date objects for your solution, you'll need to do something like this:
// Convert user input into year, month, and day integers
Date toDate = new Date(year - 1900, month - 1, day + 1);
Date currentDate = new Date();
boolean runThatReport = toDate.after(currentDate);
Shifting the toDate ahead to midnight of the next day will take care of the bug I've whined about in the comments to other answers. But, note that this approach uses a deprecated constructor; any approach relying on Date will use one deprecated method or another, and depending on how you do it may lead to race conditions as well (if you base toDate off of new Date() and then fiddle around with the year, month, and day, for instance). Use Calendar, as described elsewhere.
Use java.util.Calendar if you have extensive date related processing.
Date has before(), after() methods. you could use them as well.