Comparing Just the Date (not time) - java

I need to compare 2 dates to a third date and ignore the time portion of all of them.
The code below generates a parse exception because the toString() method returns something like "Wed Feb 26 00:00:00 EST 2014".
Any suggestions on how I might fix this?
private boolean needToSendEmail(EmSelfCertEntity escd) throws ParseException {
boolean sendEmail = false;
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date justTheDate = df.parse(escd.getCurrentFCESDate().toString());
Calendar firstSent = Calendar.getInstance();
firstSent.setTime(justTheDate);
justTheDate = df.parse(new Date().toString());
Calendar firstFollowUp = Calendar.getInstance();
firstFollowUp.setTime(justTheDate);
firstFollowUp.add(Calendar.DATE, -daysToFirstFollowUpEmail);
Calendar secondFollowUp = Calendar.getInstance();
secondFollowUp.setTime(justTheDate);
secondFollowUp.add(Calendar.DATE, -daysToSecondFollowUpEmail);
if ((firstSent.before(firstFollowUp) && escd.countEmailsSent <= 1)
|| (firstSent.before(secondFollowUp) && escd.countEmailsSent <= 2)) {
sendEmail = true;
}
return sendEmail;
}
Thanks!

Why are you parsing the String when you already have the Date?
If you want to format your existing Date into the format you specified, use the format() method instead:
String justTheDate = df.format(new Date());
Then you can compare the Strings using the equals() method to check for matches.
Edit- By the way, if Java 8 is an option (it came out on Tuesday!), its new DateTime features will do exactly what you're looking for: http://docs.oracle.com/javase/tutorial/datetime/

The cause for your exception is that toString in escd.getCurrentFCESDate().toString()
delivers another format than "MM/dd/yyyy".
So make sure that either your format String in line SimpleDateFormat("MM/dd/yyyy") is correct.
Or check if you can get the year, month, and day directly from getCurrentFCESDate().
Just Use the calendar to create a date, where you take the year, months, day from the existing date but set the hours, minutes, seconds and millis to zero.
The result will be a Date object:
Something like
firstSent.set(Calendar.HOUR, 0);
firstSent.set(Calendar.MINUTE, 0);
firstSent.set(Calendar.SECOND, 0);
firstSent.set(Calendar.MILLISECOND, 0);
Then use before() and after()

The easiest approach would be to convert the dates to numbers in this format: yyyyMMdd.
And after that you can just compare the numbers.
But yes, please work with timezone adjustments before converting to numbers.

you can calculate the time in millis and substract the time with a simple / division.
This way you can compare 2 longs and check if one is bigger than another.
Take this example where we get to different dates for today (500 milliseconds from one to another) but... if you divide by 86400000 then... you get the same number.
Try this:
public static void main(String[] args) throws Exception {
Date d1= new Date();
Thread.sleep(500);
Date d2= new Date();
final int MILLISECONDS = 1000;
final int SECONDS = 60;
final int MINUTES = 60;
final int HOURS = 24;
final long MILLI_PER_DAY= MILLISECONDS*SECONDS*MINUTES*HOURS;
System.out.println(MILLI_PER_DAY);
System.out.println(d1.getTime());
System.out.println(d2.getTime());
System.out.println(d1.getTime()/MILLI_PER_DAY);
System.out.println(d2.getTime()/MILLI_PER_DAY);
}
You will see that the last 2 entries are the same:
1395338535623 --> time 1 in millis
1395338536123 --> time 2 in millis
16149 --> time 1 / 86400000
16149 --> time 2 / 86400000 --> THE SAME

Related

How do I figure out whether the current time is in between two times? [duplicate]

This question already has answers here:
How can I determine if a date is between two dates in Java? [duplicate]
(11 answers)
Closed 9 years ago.
I'm trying to write a schedule program in Java and I need to figure out what time it is, and whether the current time is in between two set times. Figuring out the current time is pretty simple, but do you have any suggestions for figuring out whether it is between two times of day. For example, it is 9:33 AM on a Thursday. So I would need to figure out which scheduled section of the week that time corresponds to. How would I go about comparing the time to set periods during the week, for example an Array of sectioned times during a week such as {Monday from 9-10 AM, Tuesday from 3-4 PM, Thursday from 8-11 AM}, and seeing which section of time the current time falls between?
An efficient way to find which period any date lies within would be to have a class;
public class TimePeriod implements Comparable<TimePeriod>{
Date start;
Date end;
//Constructor, getters, setters
boolean isIn(Date date) {
return date.after(start) && date.before(end);
}
public int compareTo(TimePeriod other) {
return start.compareTo(other.start);
}
}
..and then create a sorted list of TimePeriod where you can perform a binary search.
edit:
This might make the binary search easier;
int check(Date date) {
if (isIn(date)) {
return 0;
} else if (start.after(date)) {
return -1;
} else if (end.before(date)) {
return 1;
} else {
throw new IllegalStateException("Time has gone badly wrong");
}
}
If you're using Date Class, you could do it like this
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
Date before = sdf.parse("07/05/2012 08:00");
Date after = sdf.parse("07/05/2012 08:30");
Date toCheck = sdf.parse("07/05/2012 08:15");
//is toCheck between the two?
boolean isAvailable = (before.getTime() < toCheck.getTime()) && after.getTime() > toCheck.getTime();
EDITED
As suggested by Jonathan Drapeau you could also use compareTo.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
Date before = sdf.parse("07/05/2012 08:00");
Date after = sdf.parse("07/05/2012 08:30");
Date toCheck = sdf.parse("07/05/2012 08:15");
//is toCheck between the two?
if you want to include the "initial" and "final" date range
boolean isAvailable = before.compareTo(toCheck) >= 0 && after.compareTo(toCheck) <= 0
if you want to exclude the "initial" and "final" date range
boolean isAvailable = before.compareTo(toCheck) > 0 && after.compareTo(toCheck) < 0
You could use it too on Calendar class.
Anyway, i highly recommend you to use Calendar. It's a way precise class
you could check it like this:
Calendar cal1 = Calendar.getInstance(); // for example 12:00:00
Calendar cal2 = Calendar.getInstance(); // for exmaple 12:30:00
Calendar userTime = Calendar.getInstance(); // time to test: 12:15:00
if(user.after(cal1)&& user.before(cal2)){
//...
}
And to initialize and set times to Calendar, check this:
http://www.tutorialspoint.com/java/util/calendar_settime.htm
I would suggest using the Epoch time.
For a definition of Epoch time: http://en.wikipedia.org/wiki/Epoch_time
Basically, its a number of seconds after a specific date, i believe in 1989. If you translate the 3 times (the current time and the 2 times to compare to) in epoch time you can just use > < = etc.
For information on getting epoch time, Try here (has many languages): http://shafiqissani.wordpress.com/2010/09/30/how-to-get-the-current-epoch-time-unix-timestamp/
Unfortunately, my java is lacking or I'd give you some code :)
Edit:
Java epoch time code:
long epoch = System.currentTimeMillis()/1000;
Because my Java is bad and I don't have an interpreter where I am, I can only suggest using this site to help convert the other dates to epoch time: http://www.epochconverter.com/
There is before(Date) and after(Date) method in Date Class.
secondDate.before(firstDate)
If you use Calendar class, it has explicit before() and after() methods:
Calendar startDate = ...
Calendar endData = ...
isBetween = currentDate.after(startDate) && currentDate.before(endDate);

Dates are not getting compared?

I am comparing dates in my android application, how ever for my equal dates, compareTo or equals method returns me that dates are not equal. I have debugged through and I can see both my objects have same values. But some how it is not working. Following is the way I am doing it:
public static boolean compareDates(long deliveryTime, Date date) throws ParseException {
Date deliveryDate = convertLongToDate(deliveryTime);
deliveryDate.setHours(0);
deliveryDate.setMinutes(0);
deliveryDate.setSeconds(0);
if (deliveryDate.equals(date))
{
return true;
}
return false;
}
My date object does not contain time, so I am setting deliverTime's time to 0(zero) as well, so that both objects can have same values. but it does not work. Any help is appreciated. Thanks!
I would create a Date object out of the deliveryTime, and then compare the hours, minutes and seconds. A code is below.
public static boolean compareDates(long deliveryTime, Date date) {
Date d = new Date(deliveryTime);
return(d.getHours() == date.getHours() && d.getMinutes() == date.getMinutes() && d.getSeconds() == date.getSeconds());
}
Would it not be easier to just compare deliveryTime to date.getTime() instead of converting deliveryTime to a Date?
Edit
Since you didn't mention you want to ignore milliseconds, you could do:
(deliveryTime / 1000) == (date.getTime() / 1000)
That should strip out the milliseconds. Alternatively,
Calendar c = Calendar.getInstance();
c.setTime(deliveryTime);
c.set(Calendar.MILLISECOND, 0);
//Clear out the other fields you don't care to compare
Date deliveryDate = c.getTime()
If you make date and deliverydate into date objects, then you can use
date.compareTo(deliveryDate);
This will return: 0 if the dates are the same, a value greater than 0 if date is more recent than deliveryDate, and a value less than 0 if date is before deliveryDate.
To get your dates into date format, you can use something like the following:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(date);
Date deliveryDate = sdf.parse(deliveryTime);

how to check : dateOne < dateTwo

I need help to check following conditions related to date and time...
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String CurrentDate= dateFormat.format(cal.getTime());
String ModifiedDate = dateTime taken from date n time picker widget ;
i have to check :
current ModifiedDate is not less than 5 minutes of current time
How to check this conditon in Android / Java..........?
Why are you formatting the date?
It's much easier to work with data in a "natural" representation rather than in a string representation. It's not clear whether your modified date has to be taken as a string, but if it does, the first thing you should do is parse it. You can then compare that with the current date and time using:
// Check if the value is later than "now"
if (date.getTime() > System.currentTimeMillis())
or
// Check if the value is later than "now + 5 minutes"
if (date.getTime() > System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(5))
It's not really clear what you mean by "current ModifiedDate is not less than 5 minutes of current time" - whether you mean that it's not less than 5 minutes after, or not less than 5 minutes earlier, or something like that - but you should be able to change the code above to handle your requirements.
If you do a lot of date/time manipulation, I'd strongly recommend the use of Joda Time, which is a much better date/time API than java.util.Date/Calendar.
To check whether the given time is before/after the current time ,
There is a Calendar instance in Android...to compare date time values.
Calendar current_time = Calendar.getInstance ();
current_time.add(Calendar.DAY_OF_YEAR, 0);
current_time.set(Calendar.HOUR_OF_DAY, hrs);
current_time.set(Calendar.MINUTE, mins );
current_time.set(Calendar.SECOND, 0);
Calendar given_time = Calendar.getInstance ();
given_time.add(Calendar.DAY_OF_YEAR, 0);
given_time.set(Calendar.HOUR_OF_DAY, hrs);
given_time.set(Calendar.MINUTE, mins );
given_time.set(Calendar.SECOND, 0);
current_time.getTime();
given_time.getTime();
boolean v = current_calendar.after(given_calendar);
// it will return true if current time is after given time
if(v){
return true;
}
public static boolean getTimeDiff(Date dateOne, Date dateTwo) {
long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
int day = (int) TimeUnit.MILLISECONDS.toHours(timeDiff);
int min= (int) ( TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
if(day>1)
{
return false;
}
else if(min>5)
{
return false;
}
else
{
return true;
}
}
usage:
System.out.println(getTimeDiff(new Date("01/13/2012 12:05:00"),new Date("01/12/2012 13:00:00")));

How to write a method that returns number (int) of days from provided day to the todays date?

Please help me to write a method that returns number (int) of days from a provided day to the todays date.
So let's say, I am providing into a method an int 110515 (for May 15, 2011). It should return 9 (inclusive or exclusive is not important to me).
If you can use Joda, this is super simple:
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
Of course you could combine these.
int days = Days.daysBetween(startDate, endDate).getDays();
Joda objects can go back and forth between the JDK's date class pretty easily.
For the first part, make a DateFormatter then parse the string based on it, like this:
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd");
DateTime dt = fmt.parseDateTime(strInputDateTime);
(After turning the int into a string of course.)
Should dates in the future include the current day? Meaning if today is May 24th 2011, should 110529 result in 4 or 5?
public static long numberOfDays(final long date) throws ParseException {
final Calendar compare = Calendar.getInstance();
compare.setTime(new SimpleDateFormat("yyMMdd").parse(String.valueOf(date)));
final int dstOffset = compare.get(Calendar.DST_OFFSET);
final long currentTimeMillis = System.currentTimeMillis();
final long compareTimeInMillis = compare.getTimeInMillis();
long difference = 0;
if (currentTimeMillis >= compareTimeInMillis) {
difference = currentTimeMillis - compareTimeInMillis - dstOffset;
} else {
difference = compareTimeInMillis - currentTimeMillis + dstOffset;
}
return difference / (24 * 60 * 60 * 1000);
}
Since this seems like a homework question I will help you out. You will want to use Calendar.getTimeInMillis. Then you will want to create a constant that is NUMBER_OF_MILLIS_IN_DAY . From there you subtract the initialDate from the currentDate (both time in millis) and divide by the constant.

How to compare Time in java/android (given input in strings)?

I have two strings which are used to store time in the format hh:mm.I want to the compare these two to know which time is greater.Which is the easiest way to go about this?
Use the SimpleDateFormat and Date classes. The latter implements Comparable, so you should be able to use the .compareTo() method to do the actual comparison. Example:
String pattern = "HH:mm";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
Date date1 = sdf.parse("19:28");
Date date2 = sdf.parse("21:13");
// Outputs -1 as date1 is before date2
System.out.println(date1.compareTo(date2));
// Outputs 1 as date1 is after date1
System.out.println(date2.compareTo(date1));
date2 = sdf.parse("19:28");
// Outputs 0 as the dates are now equal
System.out.println(date1.compareTo(date2));
} catch (ParseException e){
// Exception handling goes here
}
See the SimpleDateFormat documentation for patterns.
Well, if they're actually hh:mm (including leading zeroes, and in 24-hour format) then you can just compare them lexicographically (i.e. using String.compareTo(String)). That's the benefit of a sortable format :)
Of course, that won't check that both values are valid times. If you need to do that, you should probably parse both times: check the length, check the colon, parse two substrings, and probably multiply the number of hours by 60 and add it to the number of minutes to get a total number of minutes. Then you can compare those two totals.
EDIT: As mentioned in the comments, if you do need to parse the values for whatever reason, personally I would recommend using Joda Time (possibly a cut down version, given the mobile nature) rather than SimpleDateTimeFormat and Date. Joda Time is a much nicer date and time API than the built-in one.
I have written functions for this before in my Android program and I will gladly share the source below.
Functions (will explain later using "how to use" code):
public static void String setFormattedTimeString(final String formatExpr,
final long timeStampInSeconds) {
final Date dateFromTimeStamp = new Date(timeStampInSeconds);
final SimpleDateFormat simpleformat = new SimpleDateFormat(formatExpr);
final String formattedDateInString = simpleformat.format(dateFromTimeStamp);
return formattedDateInString;
}
public static void Calendar setCalendar(final int year, final int month,
final int day) {
final Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, day);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.YEAR, year);
return calendar;
}
public static void double timeDifferenceInDays(final Calendar firstDate,
final Calendar secondDate) {
final long firstDateMilli = firstDate.getTimeInMillis();
final long secondDateMilli = secondDate.getTimeInMillis();
final long diff = firstDateMilli - secondDateMilli;
// 24 * 60 * 60 * 1000 because I want the difference in days. Change
// as your wish.
final double diffDays = (double) diff / (double) (24 * 60 * 60 * 1000);
return diffDays;
}
And this is how I use them to calculate difference (days in this example). In this example I'm assuming you have a timestamp to use, otherwise you can change easily:
// Here you maybe have a timestamp in seconds or something..
// This is ONE Calendar.
final String yearString = MyToolClass.setFormattedTimeString("y", timestamp);
final int year = Integer.parseInt(yearString);
final String monthString = MyToolClass.setFormattedTimeString("M", timestamp);
final int month = Integer.parseInt(monthString);
final String day_in_monthString = MyToolClass.setFormattedTimeString("d",
timestamp);
final int day_of_month = Integer.parseInt(day_in_monthString);
final Calendar calendarOne = MyToolClass.setCalendar(year, month,
day_of_month);
// Same stuff for Calendar two.
// Calculate difference in days.
final double differenceInDays = MyToolClass.timeDifferenceInDays(calendarOne,
calendarTwo);

Categories