ANDROID - 如何显示已经过去的日期时间?

ANDROID - How to display datetime that already passed?

我想用特定的时间和日期显示已经过去的时间。

示例:

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

TextView 只会显示 0 Years 0 Month 1 Days 00 Hours 00 Minutes 01 Seconds already passed_

如果有人能提供最适合我的关键字,我将不胜感激。

Ref: link1 但不足以解决我的问题。

您需要创建 Date 个对象的 Calendar 个对象并比较它们以了解经过了多少时间。

或者您可以使用 Joda 日期时间库来查找它。

Check out

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

应该给你你想要的。

要获得两个日期之间的差异,您可以使用 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 ).

首先我将字符串解析为 LocalDateTime 对象,然后我得到了这些日期之间的差异。 API 创造了 2 个不同的 "time-difference/amount of time" 概念:Period、基于日期的时间量(以年、月和日表示)和 Duration ,一个基于时间的量(以秒为单位)。

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
        }
    }
}

输出为:

1 day 1 second


请注意,Period class 已经将字段(年、月和日)分隔开,而 Duration class 仅保留秒(所以一些需要计算才能得到正确的结果)——它实际上有像 toHours() 这样的方法,但它只是将秒转换为小时,并且没有像我们想要的那样分隔所有字段。

您可以将 append() 方法自定义为您想要的确切格式。我只是采用了打印的简单方法value + text,但是你可以根据需要更改它。


Java新Date/TimeAPI

对于 Java >= 8,有 new java.time API. You can use this new API and the ThreeTen Extra project,其中有 PeriodDuration class(Period 和 [=14 的组合=]).

代码与上面基本相同,唯一不同的是包名(在Java8中是java.time,在ThreeTen Backport(或Android的ThreeTenABP)是 org.threeten.bp),但是 classes 和方法 names 是相同的。

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

当然你也可以使用org.threeten.bp版本的相同代码创建PeriodDuration

您可以使用 java.time.Duration and java.time.Period which were introduced with Java-8 as part of JSR-310 implementation to model ISO_8601#Durations。使用 Java-9,添加了一些更方便的方法。

演示:

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 ############################
    }
}

输出:

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

Trail: Date Time.

了解现代日期时间 API
  • 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它向后移植了大部分 java.time Java 6 和 7 的功能。
  • 如果您正在为 Android 项目工作,并且您的 Android API 水平仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring and