-1

I want to display the time that already passed with specific time and date.

Example :

time1 = 2017-06-18 07:00:00 //set time
curtime = 2017-06-19 07:00:01 //get the current time

TextView will just display 0 Years 0 Month 1 Days 00 Hours 00 Minutes 01 Seconds already passed_

If someone have the best keyword for me to finding my self, I appreciate it.

Ref: link1 but not enough to face my issue.

dreq
  • 41
  • 7
  • 1
    Please share the code that you have come up with so far. – Sufian Jun 19 '17 at 11:42
  • https://stackoverflow.com/a/18719181/3395198 – IntelliJ Amiya Jun 19 '17 at 11:43
  • @Sufian i'm notyet type the code because i'm stuck from where should i start – dreq Jun 19 '17 at 11:43
  • @dreq use `compareTo` – IntelliJ Amiya Jun 19 '17 at 11:44
  • @IntelliJAmiya are you sure the link given is dynamically? because im comparing specific time with current time – dreq Jun 19 '17 at 11:46
  • 1
    @dreq please do some search and put some effort in solving the question. You will find some questions very similar to what you're trying to achieve. Please also read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask). – Sufian Jun 19 '17 at 12:00
  • @IntelliJAmiya the link given is just displaying if date1 is higher or lower then date2, but i need more result like `10-2=8` and not like `10-2=10 is bigger then 2` – dreq Jun 19 '17 at 12:12
  • @Sufian thans for the suggesting, but as you see above, i've tried to find the tutorial about my issue, but till now i got nothing – dreq Jun 19 '17 at 12:13
  • @dreq the link you gave is for count down timer, but your question is a bit simple. If you show the code that you've worked out, it will help us understand where you're stuck. – Sufian Jun 19 '17 at 13:56

4 Answers4

1

Check DateUtils: https://developer.android.com/reference/android/text/format/DateUtils.html#getRelativeTimeSpanString(long,long,long)

Should give you what you are looking for.

Raanan
  • 4,664
  • 25
  • 45
1

To get the difference between 2 dates, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).

First I parsed the strings to a LocalDateTime object, then I've got the difference between those dates. The API has created 2 different concepts of "time-difference/amount of time": a Period, a date-based amount of time (in terms of years, months and days), and a Duration, a time-based amount (in terms of seconds).

import org.threeten.bp.Duration;
import org.threeten.bp.LocalDate;
import org.threeten.bp.LocalDateTime;
import org.threeten.bp.LocalTime;
import org.threeten.bp.Period;
import org.threeten.bp.format.DateTimeFormatter;

String time1 = "2017-06-18 07:00:00"; // set time
String curtime = "2017-06-19 07:00:01"; // get the current time

// parse the strings to a date object
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime t1 = LocalDateTime.parse(time1, fmt);
LocalDateTime cur = LocalDateTime.parse(curtime, fmt);

// get the period between the dates
LocalDate startDate = t1.toLocalDate();
LocalDate endDate = cur.toLocalDate();
Period period = Period.ZERO;
if (startDate != null && endDate != null) {
    period = Period.between(startDate, endDate);
}

// get the duration between the dates
LocalTime startTime = t1.toLocalTime();
LocalTime endTime = cur.toLocalTime();
startTime = startTime != null ? startTime : LocalTime.MIDNIGHT;
endTime = endTime != null ? endTime : LocalTime.MIDNIGHT;
Duration duration = Duration.between(startTime, endTime);

StringBuilder sb = new StringBuilder();
append(sb, period.getYears(), "year");
append(sb, period.getMonths(), "month");
append(sb, period.getDays(), "day");
long seconds = duration.getSeconds();
long hours = seconds / 3600;
append(sb, hours, "hour");
seconds -= (hours * 3600);
long minutes = seconds / 60;
append(sb, minutes, "minute");
seconds -= (minutes * 60);
append(sb, seconds, "second");

System.out.println(sb.toString()); // 1 day 1 second

// auxiliary method
public void append(StringBuilder sb, long value, String text) {
    if (value > 0) {
        if (sb.length() > 0) {
            sb.append(" ");
        }
        sb.append(value).append(" ");
        sb.append(text);
        if (value > 1) {
            sb.append("s"); // append "s" for plural
        }
    }
}

The output is:

1 day 1 second


Note that the Period class already keeps the fields (years, months and days) separated, while the Duration class keeps only the seconds (so some calculations are needed to get the correct results) - it actually has methods like toHours(), but it only converts the seconds to hours, and it doesn't separate all the fields like we want.

You can customize the append() method to the exact format you want. I just took the simple approach of printing value + text, but you can change it according to your needs.


Java new Date/Time API

For Java >= 8, there's the new java.time API. You can use this new API and the ThreeTen Extra project, which has the PeriodDuration class (a combination of both Period and Duration).

The code is basically the same as above, the only difference is the packages names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.

import org.threeten.extra.PeriodDuration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

String time1 = "2017-06-18 07:00:00"; // set time
String curtime = "2017-06-19 07:00:01"; // get the current time

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime t1 = LocalDateTime.parse(time1, fmt);
LocalDateTime cur = LocalDateTime.parse(curtime, fmt);

PeriodDuration pd = PeriodDuration.between(t1, cur);

StringBuilder sb = new StringBuilder();
append(sb, pd.getPeriod().getYears(), "year");
append(sb, pd.getPeriod().getMonths(), "month");
append(sb, pd.getPeriod().getDays(), "day");
long seconds = pd.getDuration().getSeconds();
long hours = seconds / 3600;
append(sb, hours, "hour");
seconds -= (hours * 3600);
long minutes = seconds / 60;
append(sb, minutes, "minute");
seconds -= (minutes * 60);
append(sb, seconds, "second");

System.out.println(sb.toString()); // 1 day 1 second

Of course you can also create a Period and a Duration using the same code of org.threeten.bp's version.

0

You need to create Date objects of Calendar objects and compare them to know how much time has passed.

Or you can use the Joda date time library to find it.

Check out

gprathour
  • 13,193
  • 5
  • 56
  • 85
0

You can use java.time.Duration and java.time.Period which were introduced with Java-8 as part of JSR-310 implementation to model ISO_8601#Durations. With Java-9, some more convenience method were added.

Demo:

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u-M-d H:m:s", Locale.ENGLISH);
        LocalDateTime startDateTime = LocalDateTime.parse("2017-06-18 07:00:00", dtf);

        // Use the following line for the curren date-time
        // LocalDateTime endDateTime = LocalDateTime.now(); 

        // Use the following line for a given end date-time string
        LocalDateTime endDateTime = LocalDateTime.parse("2017-06-19 07:00:01", dtf);

        Period period = startDateTime.toLocalDate().until(endDateTime.toLocalDate());
        Duration duration = Duration.between(startDateTime, endDateTime);

        // ############################ Java-8 ############################
        String periodDuration = String.format("%d Years %d Months %d Days %02d Hours %02d Minutes %02d Seconds",
                period.getYears(), period.getMonths(), period.getDays(), duration.toHours() % 24,
                duration.toMinutes() % 60, duration.toSeconds() % 60);
        System.out.println(periodDuration);
        // ############################ Java-8 ############################

        // ############################ Java-9 ############################
        periodDuration = String.format("%d Years %d Months %d Days %02d Hours %02d Minutes %02d Seconds",
                period.getYears(), period.getMonths(), period.getDays(), duration.toHoursPart(),
                duration.toMinutesPart(), duration.toSecondsPart());
        System.out.println(periodDuration);
        // ############################ Java-8 ############################
    }
}

Output:

0 Years 0 Months 1 Days 00 Hours 00 Minutes 01 Seconds
0 Years 0 Months 1 Days 00 Hours 00 Minutes 01 Seconds

Learn about the modern date-time API from Trail: Date Time.

Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72