0

So I have this code right now:

long diff = dateTwo.getTime() - dateOne.getTime();
long seconds = diff/1000;
long minutes = seconds/60;
long hours = minutes/60;
long days = hours/24;
long years = days/365;

And this gets me the elapsed time in minutes, seconds, days and years, but I want to have a timer that shows something like: Time passed - 1 year, 20 days, 5 minutes, 20 seconds. How can I make an algorithm that takes into account leap years and displays the numbers correctly?

dumbPotato21
  • 5,669
  • 5
  • 21
  • 34
  • 1
    If you use Java 8 then look into the new date and time library. It is very easy to do this. – Thorbjørn Ravn Andersen May 14 '17 at 18:17
  • Can you point me to a link, please? I searched the internet but haven't stumbled upon anything – ubuntuaskdanidani May 14 '17 at 18:19
  • [link](http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html) and [this one as well](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) – Bill F May 14 '17 at 18:20
  • Android is not yet Java 8. Bug google. – Thorbjørn Ravn Andersen May 14 '17 at 19:05
  • You can use the newer `java.time` classes from JSR-310 on Android alright, @ThorbjørnRavnAndersen. See [this question: How to use ThreeTenABP in Android Project](http://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project) and its great and thorough answer. – Ole V.V. May 14 '17 at 19:29
  • @ubuntuaskdanidani, do you want months too (if there are any)? I take it from your example that you don’t want weeks. – Ole V.V. May 15 '17 at 07:26

3 Answers3

2

You can use the getters of java.time.LocalDateTime for that.

LocalDateTime now = LocalDateTime.now();
LocalDateTime past = LocalDateTime.of(someYear,someMonth...)
int year = now.getYear() - past.gerYear();
int month = now.getMonthValue() - past.getMonthValue();
int day = now.getDayOfMonth() - past.getDayOfMonth();
int hour = now.getHour() - past.getDayOfHour();
int minute = now.getMinute() - past.getMinute();
int second = now.getSecond() -past.getSecond();
int millis = now.get(ChronoField.MILLI_OF_SECOND) - past.get(ChronoField.MILLI_OF_SECOND);  

notice that you need to use some if else statements to check which value is bigger and subtract from it the other

Yan.F
  • 630
  • 5
  • 20
2

I ended up doing this:

 diff = dataDoi.getTime() - dataPrima.getTime();
 x = TimeUnit.MILLISECONDS.toSeconds(diff);
 seconds = x % 60;
 x /= 60;
 minutes = x % 60;
 x /= 60;
 hours = x % 24;
 x /= 24;
 days = x % 365;
 x /= 365;
 years = x;

By diving every time, you get the remaining time only.

1

You need to check result of dividing years of 4 because when leap years divide on 4 we will have 0:

if(years % 4 == 0) {
 // to do something
}
Vasyl Lyashkevych
  • 1,920
  • 2
  • 23
  • 38