I am looking for to calculate the time difference between two calendar dates and need the result difference in minutes. Below is what I am trying but it says: can't apply - operator. My page.getLastModified().getTime() gives me Calendar object. Any idea how can I achieve this.
long lastModified = page.getLastModified().getTime() - Calendar.getInstance().getTime();
getTime() returns Date instance and there is no overloaded - operator for Date. You may try with getTimeInMillis() to get difference milliseconds between two dates. You can later convert these milliseconds to minutes for instance with
TimeUnit.MILLISECONDS.toMinutes(durationInMillis)
I generally make use of
Joda Time
Simply because it has functions to give you the time between two dates.
Read into this previous post Usage for more info on how to.
Related
I am working on a project in my CIS 163 class that is effectively a campsite reservation system. The bulk of the code was provided and I just have to add certain functionalities to it. Currently I need to be able to determine how much time has passed between 2 different GregorianCalendar instances (one being the current date, the other being a predetermined "check out") represented by days. I haven't been able to figure out quite how to do this, and was hoping someone here might be able to help me out.
The GregorianCalendar is old and you shouldn't really use it anymore. It was cumbersome and was replaced by the "new" java.time module since Java 8.
Still, if you need to compare using GC instances, you could easily calculate time using milliseconds between dates, like this:
GregorianCalendar date1 = new GregorianCalendar();
GregorianCalendar date2 = new GregorianCalendar();
// Adding 15 days after the first date
date2.add(GregorianCalendar.DAY_OF_MONTH, 15);
long duration = (date2.getTimeInMillis() - date1.getTimeInMillis() )
/ ( 1000 * 60 * 60 * 24) ;
System.out.println(duration);
If you want to use the new Time API, the following code would work.
LocalDate date1 = LocalDate.now();
LocalDate date2 = date1.plusDays(15);
Period period = Period.between(date1, date2);
int diff = period.getDays();
System.out.println(diff);
If you need to convert between the types (e.g. you're working with legacy code), you can do it like this:
LocalDate date3 = gcDate1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate date4 = gcDate2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
Also I'm pretty sure this question must've been asked over and over again, so make sure you search properly before asking.
Since you have been forced to use the old and poorly designed GregorianCalendar class, the first thing you should do is convert each of the two GregorianCalendar objects to a modern type. Since Java 8 GregorianCalendar has a method that converts it to ZonedDateTime. Check the documentation, I include a link below.
Now that you’ve got two ZonedDateTime objects, there are different paths depending on your exact requirements. Often one will use Duration.between() for finding the duration, the amount of time between them in hours, minutes, seconds and fraction of second. If you know that you will always need just one of those time units, you may instead use for example ChronoUnit.HOURS.between() or ChronoUnit.MILLISECONDS.between(). If you need to count days, use ChronoUnit.DAYS.between().
If instead you need the time in months and days, you should instead use Period.between().
Links
Documentation:
GregorianCalendar (long outdated, don’t use unless forced to)
Duration
ChronoUnit
Period
Oracle tutorial: Date Time explaining how to use java.time, the modern Java date and time API to which ZonedDateTIme, Duration, ChronoUnit and Period belong.
in Java I'm trying to compare two different hours by converting them to milliseconds if (20:00 > 19:30) // do anything. In millis, it would be if (72000000 > 70200000) // do anything
But the smartphone doesn't do it well. I'm storing the numbers in variables long, as in the class Calendar, the method myCal.getTimeInMillis() returns a long, but it doesn't work.
I have tried changing the data type of the variables from long to double and it does work, so I figure out that those large numbers simply "doesn't fit" in the variable, but then, why the Java Calendar method getTimeInMillis() returns a long?
How does time work in Java Calendar? Thanks in advance.
Edit:
Thank you for your answers and time, I'm sorry for this question because it does work to compare different hours which are stored in long variables. I have tried again and it does work (I don't know why it didn't work before). I'm making an alarm clock app for Android and I want to compare not only two hours (and minutes and seconds), but also day of the week and so on. So I'm going to mark as the solution of this question the answer of #Sufiyan Ghori because I think it can really help me, and I think I'm gonna delete this question because it has no sense.
I'm new here (and in programming in general), so sorry for this silly question.
instead of comparing hours after converting it into milliseconds you can use Date::before or Date::after methods after setting your time into two separate Date objects.
Date date1 = new Date(); // set time for first hour.
Date date2 = new Date(); // set time for second hour.
You can use Calendar to set time for each Date object, like this,
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,12);
cal.set(Calendar.MINUTE,10);
cal.set(Calendar.SECOND,31);
cal.set(Calendar.MILLISECOND,05);
date1 = cal.getTime(); //set time for first hour
and then use these for comparison,
if(date1.after(date2)){
}
if(date1.before(date2)){
}
and Date::equals,
if(date1.equals(date2)){
}
getTimeInMillis() doesn't return milliseconds passed from the start of the current day, it returns millisecons passed since 01 Jan 1970 00:00:00 GMT.
Take a look at documentation of Calendar class: java.util.Calendar
Since the Java doc tell me, not to use System.currentTimeMillis for comparison, I started using System.nanoTime which is fine.
But I ran into some problems, I have to compare events which are in the past.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, xyz);
cal.getTimeMillis();
works fine to get the time in milliseconds, but converting it to nanoseconds (by multiplying it with 1000000) is far to inaccurate.
How can I get time of a event in the past in milliseconds?
The Calendar class in Java doesn't contain nanosecond information. So you can't get that.
You need to store the nanoseconds as long for the event you want to compare later if you need that detail.: you can't do that too, the nanoTime() is not a representation of current time, but you may still store that to evaluate elapsed time of old processes.
What data type are you using for the multiplication by 1,000,000 ? Perhaps you should use a BigDecimal, which would be accurate enough for you.
Currently I have a timestamp for example say, 2012-06-23 14:24:07.975 and
two times - 8AM and 3PM.
In java, how can I check whether the above timestamp is between the particular two time.
In other words, I need to check whether the time in timestamp (2012-06-23 14:24:07.975) falls between 8AM and 3PM or not.
Any suggestions.
You can convert the timestamp into an actual Date afterwards you convert it into a Calendar from where you can extract the hour and check it against your given hours.
Use SimpleDateFormat for getting a Date out of your Timestamp, if you cannot directly convert it.. Afterwards
Calendar cal = new GregorianCalendar();
cal.setTime(yourDate);
int hour = cal.get(Calendar.HOUR_OF_DAY);
Now do your hour check.
before and after methods should help you to do that. See docs.
I suggest using compareTo method in Date.
I have two Java instances of java.util.Date and I have to find out if they refer to the same day.
I can do this the hard way, taking the dates apart and compare the days, making sure the years match too.
Since this is such a common problem, I expect there to be an easier solution to this problem.
Thanks!
Instances of java.util.Date refer to instants in time. Which day they fall on depends on which time zone you're using. You could use a java.util.Calendar to represent an instant in a particular time zone...
... or you could use Joda Time instead, which is a much, much better API. Either way, you'll have to know what time zone you're interested in.
In Joda Time, once you've got a relevant time zone, you can convert both instants to LocalDate objects and compare those. (That also means you can compare whether instant X in time zone A is on the same day as instant Y in time zone B, should you wish to...)
I use the DateUtils class by Apache Commons Lang 2, it provides the isSameDay(Date,Date) method.
Update:
Here the link to Apache Commons Lang 3.
From elsewhen on StackOverflow
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
return fmt.format(date1).equals(fmt.format(date2));