Compare dates ignoring milliseconds? - java

Is there a way to compare two calendar objects, but ignore milliseconds?
I have written a test case that compared two calendar objects, but there is a problem. Although all of the day, month, minutes and hours match, the milliseconds doesn't matches. I get the expected date before getting the real date:
/**
* #return
*/
private Calendar getExpectedOneMonthDateFromCurrentDate() {
Calendar expectedOneMonth = Calendar.getInstance();
expectedOneMonth.add(Calendar.MONTH, -1);
return expectedOneMonth;
}
assertEquals(getExpectedOneMonthDateFromCurrentDate(),
DateRange.LAST_ONE_MONTH.getToDate());

Remove milliseconds from your calendar
cal.set(Calendar.MILLISECOND, 0);

You need to use
cal.set(Calendar.MILLISECOND, 0);
and possibly as well
cal.set(Calendar.SECOND, 0);
if you just need the minutes to match.

The solution of setting the milliseconds to 0 has an issue: if the dates are 12:14:29.999 and 12:14:30.003, you will set the dates to 12:14:29 and 12:14:30 respectively and will detect a difference where you don't want to.
I have thought about a Comparator:
private static class SecondsComparator implements Comparator<Calendar>
{
public int compare(Calendar o1, Calendar o2)
{
final long difference = o1.getTimeInMillis() - o2.getTimeInMillis();
if (difference > -1000 && difference < 1000)
return 0;
else
return difference < 0 ? 1 : -1;
}
}
public static void main(String args[])
{
Calendar c1 = Calendar.getInstance();
Utils.waitMilliseconds(100);
Calendar c2 = Calendar.getInstance();
// will return 0
System.out.println(new SecondsComparator().compare(c1,c2));
}
However, it no a good solution neither, as this Comparator breaks the following rule:
The implementer must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.
What leads to (x=y and y=z) => x=z.
So I don't see any solution... But indeed, if you define some different dates, they are different, aren't they?

IMHO the easiest way is to use truncate() from Apache Commons DateUtils (Apache Commons DateUtils) to remove the milliseconds and compare the resulting dates.

If you are on Java 8, you can use the Java Time API, specifically Calendar::toInstant(), followed by Instant::truncatedTo(). Specify the granularity of truncation using ChronoUnit enum.
myCalendar.toInstant().truncatedTo( ChronoUnit.SECONDS ) // Lop off any fractional second.
Example.
Calendar oneMonthIsh = Calendar.getInstance();
oneMonthIsh.add(Calendar.MONTH, -1);
oneMonthIsh.add(Calendar.MINUTE, 1);
assertNotEquals(oneMonthIsh.toInstant(), getExpectedOneMonthDateFromCurrentDate());
assertEquals(oneMonthIsh.toInstant().truncatedTo(ChronoUnit.DAYS),getExpectedOneMonthDateFromCurrentDate().toInstant()
.truncatedTo(ChronoUnit.DAYS));

One option is to call Calendar.set(Calendar.MILLISECOND, 0) to clear the milliseconds. Another is call getTimeInMillis() to get the time in milliseconds for both calendars. You could then divide these by 1000 before comparing to remove the milliseconds.

I'd recommend using Joda Time if you are performing anything beside the basic date manipulations. In your case you can truncate the dates like so and then compare :
DateTime dateTime = new DateTime().millisOfDay().roundFloorCopy();

clearMilis(date1).compareTo(clearMilis(date2))
/**
* #param date date
*
* #return truncated miliseconds
*/
#Nonnull
public static Date clearMillis(final #Nonnull Date date)
{
DateTime result = new DateTime(date);
return result.minusMillis(result.getMillisOfSecond()).toDate();
}

public static String getFromatDateTime(Date date) {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
final GregorianCalendar gc = new GregorianCalendar();
gc.setTime( date );
//gc.set( Calendar.HOUR_OF_DAY, 0 );
//gc.set( Calendar.MINUTE, 0 );
//gc.set( Calendar.SECOND, 0 );
//block ignore millisecond
gc.set( Calendar.MILLISECOND, 0 );
String strDate = sdfDate.format(gc.getTime());
return strDate;
}
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date now = new Date();
String currentDate = Testing.getFromatDateTime(now);
String fullDate = "2015-12-07 14:53:39.30";
String effDateStr = Testing.getFromatDateTime(sdfDate.parse(fullDate));
System.out.println("Currennt Date: " + currentDate);
System.out.println("Effective Date: " + effDateStr);
System.out.println(currentDate.compareTo(effDateStr)==0);
}

If you use jodaTime, the setCopy("0") method returns a DateTime object with milliseconds set to 0 to make it easy to compare:
DateTime dateTimeZerodMillis = new DateTime().millisOfSecond ().setCopy("0")

Though I am way too late for the party, sharing my simple alternate approach for posterity
Two date objects comparision by ignoring the milliseconds using org.apache.commons.lang3.time.DateUtils
Date date1 = new Date(1503055069000L);
Date date2 = new Date(1503055069683L);
//Here the two dates are differed by 683 milliseconds, if we want to skip just the
//683 milliseconds difference then we can use the below logic
if(DateUtils.setMilliseconds(date1, 0).equals(DateUtils.setMilliseconds(date2, 0))){
//your business process
}
NOTE: DateUtils#setMilliseconds method sets the milliseconds field to a date returning a new object. The original Date is unchanged. so until you are reassigning the object reference the original date object values are unchanged.

Related

Generating all days between 2 given dates in Java [duplicate]

This question already has answers here:
how to get a list of dates between two dates in java
(23 answers)
Closed 6 years ago.
I'm trying to get an array of Dates, while my input is a 'from'/'to' structure.
So my input is:
String date1 = "2014-01-01";
String date2 = "2014-05-01";
My output should be an Arraylist with all dates between date1 and date2.
I've already looked for this, but I could only find questions about the difference between 2 dates:
SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";
try {
Date date1 = myFormat.parse(inputString1);
Date date2 = myFormat.parse(inputString2);
long diff = date2.getTime() - date1.getTime();
System.out.println ("Days: " + TimeUnit.DAYS.convert(diff,TimeUnit.MILLISECONDS));
} catch (ParseException e) {
e.printStackTrace();
}
Any hints or suggestions? All other questions are for iOS or SQL.
Take a look at JodaTime: http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html
DateTime dateTime1 = new DateTime(date1);
DateTime dateTime2 = new DateTime(date2);
List<Date> allDates = new ArrayList();
while( dateTime1.before(dateTime2) ){
allDates.add( dateTime1.toDate() );
dateTime1 = dateTime1.plusDays(1);
}
Below is the code to get array of dates between the two string date.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
public class DateFormatExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String date1 = "2014-01-01";
String date2 = "2014-05-01";
try {
Date d1 = myFormat.parse(date1);
Date d2 = myFormat.parse(date2);
List<Date> allDates = new ArrayList<Date>();
List<String> allDatesString = new ArrayList<String>();
while( d1.before(d2) ){
d1 = addDays(d1, 1);
allDates.add(d1);
allDatesString.add(formatter.format(d1));
}
System.out.println(allDates);
System.out.println(allDatesString);
} catch (ParseException e) {
e.printStackTrace();
}
}
private static Date addDays(Date d1, int i) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(d1);
cal.add(Calendar.DATE, 1);
return cal.getTime();
}
}
If you don't want to use third party libraries you can use Calendar:
Check here a working demo.
public static void main(String[] args) throws Exception {
SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";
ArrayList<Date> dates = new ArrayList<Date>();
try {
Date date1 = myFormat.parse(inputString1);
Calendar c1 = DateToCalendar(date1);
Date date2 = myFormat.parse(inputString2);
Calendar c2 = DateToCalendar(date2);
while (!areEqualDate(c1, c2)) {
dates.add(c1.getTime());
System.out.println (c1.getTime());
c1.add(Calendar.DAY_OF_YEAR, 1);
}
} catch (ParseException e) {
e.printStackTrace();
}
// ArrayList<Date> dates >> contain all dates between both given days.
}
private static boolean areEqualDate(Calendar c1, Calendar c2) {
if (c1.get(Calendar.YEAR) != c2.get(Calendar.YEAR)) return false;
if (c1.get(Calendar.MONTH) != c2.get(Calendar.MONTH)) return false;
if (c1.get(Calendar.DAY_OF_YEAR) != c2.get(Calendar.DAY_OF_YEAR)) return false;
return true;
}
public static Calendar DateToCalendar(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
}
I like JodaTime, but this can also be done without 3rd party libraries by using java.util.Calendar. Given a Calendar object, one can use its add method to increase certain fields of the date while honoring the calendar rules (like adding 1 day to the 31st of January gets you to the 1st of February, not to the 32nd of January).
First get the dates into one Calendar object each, in the correct chronological order so adding is going in the right direction later:
Calendar cStart = Calendar.getInstance(),
cStop = Calendar.getInstance();
if (date1.before(date2)) {
cStart.setTime(date1);
cStop.setTime(date2);
} else {
cStart.setTime(date2);
cStop.setTime(date1);
date1 and date2 are the parsed Date objects from your question, for simplicity's sake.
Next, loop over an "add 1 to day-of-year" instruction until this gets you beyond the stop date:
do {
System.out.println(pretty(cStart));
cStart.add(Calendar.DAY_OF_YEAR, 1);
} while (cStart.before(cStop));
And lastly print the stop date
System.out.println(pretty(cStop));
pretty() is just some mini method sending the calendar through a SDF, like the one you used for parsing the Strings in the first place.
This solution will print the date range, including the start and stop dates, and might need some tweaking around the edge cases (like date1==date2). Can be easily adapted to exclude the start and stop dates. Printing can be swapped for aggregation of course. To get a Date object from the calendar, use the getTime() method (returns a snapshot, not a live reference).
The documentation for the relevant (Gregorian)Calendar can be found here.
In case you are using Guava, there is a very elegant solution to this problem.
Guava has two neat classes, such as Range and ContiguousSet, which implement exactly what you need: first one operates on ranges of values, and second one - is able to convert a range to a set of discrete values.
Example of usage of both (together with JodaTime):
LocalDate start = LocalDate.parse("2015-01-01");
LocalDate end = LocalDate.parse("2019-02-01");
Range<LocalDate> range = Range.closed(start, end); //Creates a "closed" range, that is both dates are inclusive. There are also options like "openClosed", "closedOpen" and "open"
final Set<LocalDate> daySet = ContiguousSet.create(range, LocalDateDomain.INSTANCE); //Create a "virtual" set of days in given the range. "virtual" part means that if you create a set of 10 thousand years, it will not eat your memory at all
for (LocalDate day : daySet) {
//...operation...
}
Personally, I really prefer this way, as it eliminates some problems with understanding closed/open ranges, and makes code much easier to read and understand, while making no impact on performance. Also, it works with any kinds of dates, any libraries (you can swap YodaTime to Java8 Dates or even Java7- Date-based implementation).
Moreover, it allows you to do some neat operations on ranges like intersections, unions, spanning of ranges, incredibly fast "contains" and so on.
Only downsides are:
Dependence on Guava.
Need to create a special "DiscreteDomain" class, which Guava uses to understand where one date ends and other begins.
Example of LocalDateDomain implementation which operates as a bridge between Guava and JodaTime:
public class LocalDateDomain extends DiscreteDomain<LocalDate> {
public static final LocalDateDomain INSTANCE = new LocalDateDomain();
#Override
public LocalDate next(LocalDate value) {
return value.plusDays(1);
}
#Override
public LocalDate previous(LocalDate value) {
return value.minusDays(1);
}
#Override
public long distance(LocalDate start, LocalDate end) {
return Days.daysBetween(start, end).getDays();
}
}
I already know that OP isn't using Java 8 but here's the current solution - Java has been revamped and the new java.time API does every conceivable job in that regard:
//change these values :
LocalDate ld1 = LocalDate.ofEpochDay(0);
LocalDate ld2 = LocalDate.now();
//do NOT change these:
final LocalDate begin = ld1.isBefore(ld2) ? ld1 : ld2;
final LocalDate end = ld2.isAfter(ld1) ? ld2 : ld1;
for (int i = 0; i < begin.until(end, ChronoUnit.DAYS); i++) {
final LocalDate curDate = begin.plusDays(i);
System.out.println("current date : " + curDate);
}
This will output every valid day between the two dates whereas most of the other solutions will also give you invalid ones; heres the thing: temporal calculations need to be done on timezone-independent data - the output on the other hand may very well be timezone and/or chronology -dependent.
Thats why there are packages like java.time.format - simply calculate your time/date values and format them for your chosen region ... thats how its done correctly.
If you need to convert temporal input there are also useful functions in the time-API, i recommend doing a thorough tutorial on the subject, a few good introductions may be this and especially that :
There are two basic ways to represent time. One way represents time in
human terms, referred to as human time, such as year, month, day,
hour, minute and second. The other way, machine time, measures time
continuously along a timeline from an origin, called the epoch, in
nanosecond resolution. The Date-Time package provides a rich array of
classes for representing date and time. Some classes in the Date-Time
API are intended to represent machine time, and others are more suited
to representing human time.

Comparing hours in java

First of all forgive my English :-(
I have a problem with hours on java. Let's see it by an example:
DateFormat datos = new SimpleDateFormat ("hh:mm:ss");
Date ac, lim;
String actual,limit;
actual="18:01:23";
limit="00:16:23";
ac=datos.parse(actual);
lim=datos.parse(limit);
if(ac.compareTo(lim)==-1){.......
I need to solve this case in which limit is past midnight and actual hour is before midnight. My program says that actual has reached limit and it isn't correct because at the example, it has still 6 hours to finish.
I tried to solve it with DateFormat class but it doesnt see this case. I tried it with Time class too but its methods are deprecated.
How can I solve this?
Use HH instead of hh in your SimpleDateFormat:
DateFormat datos = new SimpleDateFormat("HH:mm:ss");
hh is the 12-hour clock (hours go from 1 to 12).
HH is the 24-hour clock (hours go from 0 to 23).
But besides that, there are other things wrong with this. Class Date is not very well suited to contain only a time. If you do this, it will be parsed as 01-01-1970 with the specified time. So 18:01:23 becomes 01-01-1970, 18:01:23 and 00:16:23 becomes 01-01-1970, 00:16:23. You probably wanted to compare 18:01:23 to 00:16:23 the next day.
Try something like this:
String actual = "18:01:23";
String limit = "00:16:23";
String[] parts = actual.split(":");
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.HOUR_OF_DAY, Integer.parseInt(parts[0]));
cal1.set(Calendar.MINUTE, Integer.parseInt(parts[1]));
cal1.set(Calendar.SECOND, Integer.parseInt(parts[2]));
parts = limit.split(":");
Calendar cal2 = Calendar.getInstance();
cal2.set(Calendar.HOUR_OF_DAY, Integer.parseInt(parts[0]));
cal2.set(Calendar.MINUTE, Integer.parseInt(parts[1]));
cal2.set(Calendar.SECOND, Integer.parseInt(parts[2]));
// Add 1 day because you mean 00:16:23 the next day
cal2.add(Calendar.DATE, 1);
if (cal1.before(cal2)) {
System.out.println("Not yet at the limit");
}
The library Joda Time is a popular Java date and time library that is much better designed than the standard Java date and calendar API; consider using it if you have to work with dates and times in Java.
With Joda Time you could do this:
String actual = "18:01:23";
String limit = "00:16:23";
DateTimeFormatter df = DateTimeFormat.forPattern("HH:mm:ss");
DateTime ac = df.parseLocalTime(actual).toDateTimeToday();
DateTime lim = df.parseLocalTime(limit).toDateTimeToday().plusDays(1);
if (ac.isBefore(lim)) {
System.out.println("Not yet at the limit");
}
As a quick and dirty solution:
final DateFormat datos = new SimpleDateFormat("HH:mm:ss");
Date ac;
final Date lim = new Date();
String actual, limit;
actual = "18:01:23";
limit = "00:16:23";
try {
ac = datos.parse(actual);
lim.setTime(ac.getTime() + TimeUnit.MINUTES.toMillis(16) + TimeUnit.SECONDS.toMillis(23));
if ( ac.before(lim) ) {
// TODO
}
} catch ( final ParseException e ) {
e.printStackTrace();
}

How to add 10 minutes to my (String) time?

I have this time:
String myTime = "14:10";
Now I want to add 10 minutes to this time, so that it would be 14:20
How can I achieve this?
Something like this
String myTime = "14:10";
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Date d = df.parse(myTime);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(Calendar.MINUTE, 10);
String newTime = df.format(cal.getTime());
As a fair warning there might be some problems if daylight savings time is involved in this 10 minute period.
I would use Joda Time, parse the time as a LocalTime, and then use
time = time.plusMinutes(10);
Short but complete program to demonstrate this:
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
LocalTime time = formatter.parseLocalTime("14:10");
time = time.plusMinutes(10);
System.out.println(formatter.print(time));
}
}
Note that I would definitely use Joda Time instead of java.util.Date/Calendar if you possibly can - it's a much nicer API.
Use Calendar.add(int field,int amount) method.
Java 7 Time API
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm");
LocalTime lt = LocalTime.parse("14:10");
System.out.println(df.format(lt.plusMinutes(10)));
You need to have it converted to a Date, where you can then add a number of seconds, and convert it back to a string.
I used the code below to add a certain time interval to the current time.
int interval = 30;
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Calendar time = Calendar.getInstance();
Log.i("Time ", String.valueOf(df.format(time.getTime())));
time.add(Calendar.MINUTE, interval);
Log.i("New Time ", String.valueOf(df.format(time.getTime())));
You have a plenty of easy approaches within above answers.
This is just another idea. You can convert it to millisecond and add the TimeZoneOffset and add / deduct the mins/hours/days etc by milliseconds.
String myTime = "14:10";
int minsToAdd = 10;
Date date = new Date();
date.setTime((((Integer.parseInt(myTime.split(":")[0]))*60 + (Integer.parseInt(myTime.split(":")[1])))+ date1.getTimezoneOffset())*60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
date.setTime(date.getTime()+ minsToAdd *60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
Output :
14:10
14:20
I would recommend storing the time as integers and regulate it through the division and modulo operators, once that is done convert the integers into the string format you require.

How to remove sub seconds part of Date object

java.util.Date gets stored as 2010-09-03 15:33:22.246 when the SQL data type is timestamp, how do I set the sub seconds to zero (e.g. 246 in this case) prior to storing the record.
The simplest way would be something like:
long time = date.getTime();
date.setTime((time / 1000) * 1000);
In other words, clear out the last three digits of the "millis since 1970 UTC".
I believe that will also clear the nanoseconds part if it's a java.sql.Timestamp.
Here is an idea:
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("S");
Date d = new Date();
System.out.println(df.format(d));
Calendar c = Calendar.getInstance();
c.set(Calendar.MILLISECOND, 0);
d.setTime(c.getTimeInMillis());
System.out.println(df.format(d));
}
java.util.Calendar can help you.
Calendar instance = Calendar.getInstance();
instance.setTime(date);
instance.clear(Calendar.SECOND);
date = instance.getTime();
Here is another way by java 8 Instant api
LocalDateTime now = LocalDateTime.now();
Instant instant = now.atZone(ZoneId.systemDefault()).toInstant().truncatedTo(ChronoUnit.SECONDS);
Date date = Date.from(instant);
or
Date now = new Date();
Instant instant = now.toInstant().truncatedTo(ChronoUnit.SECONDS);
Date date = Date.from(instant);
Alternatively, you can use Apache Commons DateUtils, for example:
DateUtils.setMilliseconds(new Date(), 0);

Date Comparison using Java [duplicate]

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.

Categories

Resources