how to check : dateOne < dateTwo - java

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")));

Related

Comparing Just the Date (not time)

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

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);

Android: compare calendar dates

In my app I´m saving when I last updated some data from my server.
Therefore I used:
long time = Calendar.getInstance().getTimeInMillis();
Now I want that the data is updated twice a year at 03.03 and 08.08.
How can I check wheater one of these two date boarders were crossed since last update?
Change them to time in mseconds and compare:
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 3);
long time2= c.getTimeInMillis();
c.set(Calendar.MONTH, Calendar.AUGUST);
c.set(Calendar.DAY_OF_MONTH, 8);
long time3= c.getTimeInMillis();
if(time>time2){
//Logic
if(time>time3){
//Logic
}
}
There is something very important which took me a while to figure it out and can be very helpful to people out there, if you are looking for an answer to any of the following questions this is for you:
Why is my date not showing correctly?
Why even when I set the time manually it is not showing right?
Why is the month and the year showing one day less than the one that I set?
For some reason Java sorts the months values like an array, what I mean is that for Java January is 0 and DECEMBER is 11. Same happens for the year, if you set December as month 12 and year as 2012, and then try to do a "system.out.println" of the month and the year, it will show my month as January and the year as 2013!!
so what should you do?
Calendar cal = new GregorianCalendar();
cal.set(2012, 11, 26); // the date I want to input is 26/12/2012 (for Java, 11 is December!)
NOW WHAT IS THE CORRECT WAY TO GET THAT DATE TO SEE IT ON THE SCREEN?
if you try to "system.out.println of yourCalendar.DATE, yourCalendar.MONTH and yourCalendar.YEAR," THAT WILL NOT SHOW YOU THE RIGHT DATE!!!!
If you want to display the dates you need to do the following:
System.out.println (calact.get (calact.DATE));
// displays day
System.out.println (calact.get (calact.MONTH)+1);
//add 1 remember it saves values from 0-11
System.out.println (calact.get (calact.YEAR));
// displays year
NOW IF YOU ARE HANDLING STRINGS THAT REPRESENT DATES, OR....
IF YOU NEED TO COMPARE DATES BETWEEN RANGES , LET'S SAY YOU NEED TO KNOW IF DATE "A" WILL TAKE PLACE WITHIN THE NEXT 10 DAYS....THIS....IS.....FOR....YOU!!
In my case I was working with a string that had format "15/07/2012", I needed to know if that date would take place within the next 10 days, therefore I had to do the following:
1 get that string date and transform it into a calendar ( StringTokenizer was used here )
this is very simple
StringTokenizer tokens=new StringTokenizer(myDateAsString, "/");
do nextToken and before returning the day, parse it as integer and return it.
Remember for month before returning substract 1.
I will post the code for the first you create the other two:
public int getMeD(String fecha){
int miDia = 0;
String tmd = "0";
StringTokenizer tokens=new StringTokenizer(fecha, "/");
tmd = tokens.nextToken();
miDia = Integer.parseInt(tmd);
return miDia;
}
2 THEN YOU CREATE THE CALENDAR
Calendar cal = new GregorianCalendar(); // calendar
String myDateAsString= "15/07/2012"; // my Date As String
int MYcald = getMeD(myDateAsString); // returns integer
int MYcalm = getMeM(myDateAsString); // returns integer
int MYcaly = getMeY(myDateAsString); // returns integer
cal.set(MYcaly, MYcalm, MYcald);
3 get my current date (TODAY)
Calendar curr = new GregorianCalendar(); // current cal
calact.setTimeInMillis(System.currentTimeMillis());
4 create temporal calendar to go into the future 10 days
Calendar caltemp = new GregorianCalendar(); // temp cal
caltemp.setTimeInMillis(System.currentTimeMillis());
caltemp.add(calact.DAY_OF_MONTH, 10); // we move into the future
5 compare among all 3 calendars
here basically you ask if the date that I was given is for sure taking place in the future AND (&&) IF the given date is also less than the future date which had 10 days more, then please show me "EVENT WILL TAKE PLACE FOR SURE WITHIN THE NEXT 10 DAYS!!" OTHERWISE SHOW ME:
"EVENT WILL NOT TAKE PLACE WITHIN THE NEXT 10 DAYS".
if((cal.getTimeInMillis() > curr.getTimeInMillis()) && (cal.getTimeInMillis()< curr.getTimeInMillis()))
{ System.out.println ("EVENT WILL TAKE PLACE FOR SURE WITHIN THE NEXT 10 DAYS!!");}
else
{ System.out.println ("EVENT WILL *NOT* TAKE PLACE WITHIN THE NEXT 10 DAYS");}
ALRIGHT GUYS AND GIRLS I HOPE THAT HELPS. A BIG HUG FOR YOU ALL AND GOOD LUCK WITH YOUR PROJECTS!
PEACE.
YOAV.
If the comparison should involve only the year, month and day then you can use this method for check if c1 is before c2. Ugly, but works.
public static boolean before(Calendar c1, Calendar c2){
int c1Year = c1.get(Calendar.YEAR);
int c1Month = c1.get(Calendar.MONTH);
int c1Day = c1.get(Calendar.DAY_OF_MONTH);
int c2Year = c2.get(Calendar.YEAR);
int c2Month = c2.get(Calendar.MONTH);
int c2Day = c2.get(Calendar.DAY_OF_MONTH);
if(c1Year<c2Year){
return true;
}else if (c1Year>c2Year){
return false;
}else{
if(c1Month>c2Month){
return false;
}else if(c1Month<c2Month){
return true;
}else{
return c1Day<c2Day;
}
}
}
used compareTo method ..and this returns integer value .if returns -ve the days before in current date else return +ve the days after come current date

Need two Date() values for Java task

This is a really simple request, but I am not quite sure the easiest/most efficient way of generating these two values.
I need to write a script that will check whether a given value is between two values. I am well aware of how this is done in SQL.
The way I need the values is somethign similar to the following.
Date testValue = new Date() //This represents the value we are testing
Date beginningOfDay = .... //This value would represent the date for
testValue at 12:00am
Date endOfDay = ... //This value would represent the date for
testValue at 11:59:59pm
Again, the Java Date() type may not be the best practice to do something like this. In the end I just need to generate three values that I can say
if testValue is after beginningOfDay && testValue is before endOfDay
//do logic
Personally I use the Calendar object for this. For example:
Date testDate = ??? //Replace with whatever source you are using
Calendar testDateCalendar = Calendar.getInstance();
testDateCalendar.setTime(testDate);
Date today = new Date();
Calendar endOfDay = Calendar.getInstance(); //Initiates to current time
endOfDay.setTime(today);
endOfDay.set(Calendar.HOUR_OF_DAY, 23);
endOfDay.set(Calendar.MINUTE, 59);
endOfDay.set(Calendar.SECOND, 59);
Calendar startOfDay = Calendar.getInstance();
startOfDay.setTime(today);
startOfDay.set(Calendar.HOUR_OF_DAY, 0);
startOfDay.set(Calendar.MINUTE, 0);
startOfDay.set(Calendar.SECOND, 0);
if (startOfDay.before(testDateCalendar) && endOfDay.after(testDateCalendar))
{
//Whatever
} else {
//Failure
}
You can use a calendar object to do this and by the way, the way you did the bounds check in your question is wrong (your date can match the before/after dates and still be considered in range). The following shows whether a date falls on a certain day of the year. It assumes that the timezones for the dateTime to check and the day are equal and that no time adjustments took place:
Date dateTime=...
Date day=...
// This is the date we're going to do a range check on
Calendar calDateTime=Calendar.getInstance();
calDateTime.setTime(dateTime);
// This is the day from which we will get the month/day/year to which
// we will compare it
Calendar calDay=Calendar.getInstance();
calDay.setTime(day);
// Calculate the start of day time
Calendar beginningOfDay=Calendar.getInstance();
beginningOfDay.set(calDay.Get(Calendar.YEAR),
calDay.Get(Calendar.MONTH),
calDay.Get(Calendar.DAY_OF_MONTH),
0, // hours
0, // minutes
0); // seconds
// Calculate the end of day time
Calendar endOfDay=Calendar.getInstance();
endOfDay.set(calDay.Get(Calendar.YEAR),
calDay.Get(Calendar.MONTH),
calDay.Get(Calendar.DAY_OF_MONTH),
23, // hours
59, // minutes
59); // seconds
// Now, to test your date.
// Note: You forgot about the possibility of your test date matching either
// the beginning of the day or the end of the day. The accepted answer
// got this range check wrong, as well.
if ((beginningOfDay.before(calDateTime) && endOfDay.after(calDateTime)) ||
beginningOfDay.equals(calDateTime) || endOfDay.equals(calDateTime))
{
// Date is in range...
}
This can be further simplified to:
Date dateTime=...
Date day=...
// This is the date we're going to do a range check on
Calendar calDateTime=Calendar.getInstance();
calDateTime.setTime(dateTime);
// This is the day from which we will get the month/day/year to which
// we will compare it
Calendar calDay=Calendar.getInstance();
calDay.setTime(day);
if (calDateTime.get(YEAR)==calDay.get(YEAR) &&
calDateTime.get(MONTH)==calDay.get(MONTH) &&
calDateTime.get(DAY_OF_YEAR)==calDay.get(DAY_OF_YEAR))
{
// Date is in range
}
Here's something I've used in my own code to determine if a file was modified on a certain day. Like the other answers in this thread, I used the Calendar.
// Get modified date of the current file
// and today's date
Calendar today = Calendar.getInstance();
Calendar modDate = Calendar.getInstance();
Date date = new Date(file.lastModified());
modDate.setTime(date);
// Convert dates to integers
int modDay = modDate.get(Calendar.DAY_OF_YEAR);
int todayDay = today.get(Calendar.DAY_OF_YEAR);
if (modDay == todayDay) {
// Do stuff
}
This might be closer to what you are looking for since you only need to see if the event falls on a certain day.

Categories