How to calculate the date difference in Android?
If you can't afford 3rd party libraries like JodaTime, then your best bet is really java.util.Calendar. You can use the Calendar#add() method in a loop to calculate the difference in years, months and days between two instances. Then to calculate the difference in hours, minutes and seconds, just do the usual math on Calendar#getTimeInMillis().
Long story short, I've posted a basic example before here. You may find it useful.
Related
I was working with a school question to figure out the algorithm to find the days between two given dates which would then be implemented in Java.
The algorithm of interest was found here:
http://www.sunshine2k.de/articles/coding/datediffindays/calcdiffofdatesindates.html
(Point 4)
It was one of the more efficient algorithms because it would have the least conditions to consider during the implementation. I understand how it works in this context, but I couldn't quite wrap my mind around the use of an origin/reference point anywhere else because it seems that a simple subtraction would get most jobs done.
Eg. To find the difference between 9 and 5,
I could just do 9-5 instead of
ref = 1
difference = (9-ref) - (5-ref)
Question: Why does using this reference/origin point work in this situation? What other situations can I consider using this reference/origin point to solve problems?
First rule of Software Engineering is "Don't reinvent the wheel".
Getting the days between two dates in Java 8 and later is trivial, there's no need to code your own algorithm:
LocalDate d2 = LocalDate.now();
LocalDate d1 = LocalDate.of(1950, Month.JANUARY, 1);
long days = d1.until(d2,ChronoUnit.DAYS);
Or even better
long days = ChronoUnit.DAYS.between(d1, d2);
To get difference between 9-th and 5-th day of the same month, you can just subtract 9-5 (if there was no calendar revolution in that period :)). But for different months and different years you must account for varying number of days in the month and varying number of days in the year.
The simplest way to account for these factors is to get absolute number of days from some origin day - so-named Julian day with our era beginning as origin
Actually, 9-5 uses a reference of 0 in the same way as (9-0) - (5-0).
Unlike numbers, where 0 is the reference point, for dates, the reference point is not obvious. Should it be 0 AD, 1900 AD, or something else? With the different number of days in months, leap years etc, the day scale is not uniform. So, it is useful to find the "distance" of a date from a common date, for e.g. 1970-01-01.
I was trying to fetch the current time in UTC in Java and came across this post: Getting "unixtime" in Java
I checked out that all solutions
new Date().getTime()
System.currentTimeMillis()
Instant.now().toEpochMillis()
return the same value. I wished to know if there is any difference between the three of them. If so then what?
There is no difference. This is just the result of the evolution of the date API over the years. There is now more than one way to do this.
As far as just getting epoch milliseconds, all three are fine. Things get more complicated as soon as formatting, calendars, timezones, durations and the like become involved.
I need to write a function that takes two timestamps and segment the time range in Days, Hours and Seconds in that order. To walk through an example, lets say the input to our function is
val start = 08-01-14 12:30:00
val end = 08-04-14 12:30:00
our function will return
min -> (08-01-14 12:30:00, 08-01-14 13:00:00)
hour -> (08-01-14 13:00:00, 08-01-14 24:00:00)
day -> (08-02-14 00:00:00, 08-03-14 24:00:00)
hour -> (08-04-14 00:00:00, 08-04-14 12:00:00)
min -> (08-04-14 12:00:00, 08-04-14 12:30:00)
I have hand rolled an implementation that works but its a little kludgy, I am looking for a) is there a library that already does that? b) if not, what would be the best way to implement this?
I believe Jodatime does support calculating time periods/ranges; http://joda-time.sourceforge.net/apidocs/org/joda/time/Period.html
I have done this before with Jodatime , it's a little bit technical, but as Jodatime is an AWESOME API for everything time-ish in Java all devs should use it - There was rumours of Jodatime replacing Javas old time-apis...
Introduction: http://www.joda.org/joda-time/
EDIT:
Here's what you're looking for: http://joda-time.sourceforge.net/apidocs/org/joda/time/Interval.html
IF you are using Jodatime interval can calculate the range/interval/period between two time-objects
Say I have 2 strings in the following format:
"09/21 10:06AM"
"09/21 10:10AM"
How do I find the time difference between these strings, stored as an int? This has to be robust enough to handle situations like 10:59AM and 11:02AM (odd number of minutes in between), 11:59AM and 12:03PM (AM to PM switch) etc. No need to worry about seconds.
Thanks!
I would suggest:
Use Joda Time instead of the built-in API; it's much nicer.
Parse into LocalDateTime values
Find the difference between them with:
Minutes period = Minutes.minutesBetween(first, second);
int minutes = period.getMinutes();
DateFormat.Parse
Calculate difference between dates.
Parse the strings to Date objects and get the difference between them in milliseconds. Then convert those milliseconds to minutes (divide by 60000 and take the ceiling of the result).
If there is a switch to daylight savings the difference can be an hour more on one day than another.
It best to use a library which does this already. JodaTime is best, but SimpleDateFormat and Date will probably do what you need.
Convert the 2 Strings to Dates.
Subtract one from the other.
Multiply the result by 1440 (Number of minutes in a day).
Round the result to an Integer.
Let me know if it works :)
Why does Joda Time allow a Period constructor to take two LocalTimes but there is no Duration constructor like that?
I want to know because it may aid in my understanding of the best use of Joda Time.
Here's my thinking: Duration is good for social convention unaware applications and the lack of awareness is what makes it different from Period. LocalTime is good for convention unaware use because it has no timezone. This suggests Duration should be used with LocalTime and vice-versa.
A Duration is the amount of time between two precise Instants in time (which are completely independent of human concepts like years, days, and seconds). LocalTimes, however, represent ambiguous points in time (they require a date and time zone to define an Instant).
It makes sense to say there's a "standard duration" (the duration of the period assuming no DST, no leap years, no leap seconds (which Joda chronologies don't support, admittedly)) between two LocalTimes, but there's not enough information to compute a "true duration". I suspect this is why Duration doesn't have that constructor.
For example, let's suppose we have two LocalTimes: one representing 1:00 AM and 4:00 AM. 99% of the time, it'd make sense to say that's a duration of 3 hours. But, if they represent times on the day of a Daylight Saving Time switch, the duration would be 2 hours or 4 hours.
Period is defined more broadly, where it make senses to have a period between two partially-defined times like LocalTimes (just "3 hours" in the example). Periods correspond easily to standard durations, so one can just call period.toStandardDuration().