本文介绍了早期Android中Java 8之前的ZonedDateTime到Date的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试替换ZonedDateTime.toInstant方法,因为该方法仅从Android的API 26起可用.
但是我的应用程序应该支持API19.
我想将ZonedDateTime转换为日期,以便执行以下操作:

I am trying to replace the ZonedDateTime.toInstant method because it is only available since API 26 for Android.
But my app is supposed to support API 19.
I want to convert the ZonedDateTime to a Date so i can do something like this:

final Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
final long millis = calendar.getTimeInMillis();

我要实现的目标如下:
我想以秒,分钟,小时等方式计算当前日期与另一个日期之间的差额...可能的最高单位获胜率,所以我会得到例如结果为5 days ago.

What i want to achieve is the following:
I want to calculate the difference between the current date and another date in Seconds, Minutes, Hours, ... the highest possible unit wins, so i would get e.g. 5 days ago as result.

推荐答案

解决方案(ThreeTen-Backport库):
它运行良好,我已经在KitKat模拟器上进行了试用.

Solution (ThreeTen-Backport Library):
It's working perfectly, i already tried it out on an KitKat emulator.

private static final ChronoUnit[] chronoUnits = {ChronoUnit.YEARS, ChronoUnit.MONTHS, ChronoUnit.DAYS, ChronoUnit.HOURS, ChronoUnit.MINUTES, ChronoUnit.SECONDS};
private static final Map<ChronoUnit, Integer> chronoUnitPluralIdMap = new HashMap<ChronoUnit, Integer>() {{
    put(ChronoUnit.YEARS, R.plurals.chrono_unit_years_ago);
    put(ChronoUnit.MONTHS, R.plurals.chrono_unit_months_ago);
    put(ChronoUnit.DAYS, R.plurals.chrono_unit_days_ago);
    put(ChronoUnit.HOURS, R.plurals.chrono_unit_hours_ago);
    put(ChronoUnit.MINUTES, R.plurals.chrono_unit_minutes_ago);
    put(ChronoUnit.SECONDS, R.plurals.chrono_unit_seconds_ago);
}};

public static String getTimeStringUntilNowFromUTC(Context context, String utcDate) {
    Instant now = Instant.now(Clock.systemUTC());
    Instant then = Instant.parse(utcDate);
    for (ChronoUnit chronoUnit : chronoUnits) {
        if (then.isSupported(chronoUnit)) {
            long units = chronoUnit.between(then, now);
            if (units > 0) {
                //noinspection ConstantConditions
                return context.getResources().getQuantityString(chronoUnitPluralIdMap.get(chronoUnit), (int)units, (int)units);
            }
        }
    }
    return "-";
}

public static String getTimeBetweenTwoDates(Context context, String date1, String date2) {
    Instant date1Instant = Instant.parse(date1);
    Instant date2Instant = Instant.parse(date2);
    final long seconds = ChronoUnit.SECONDS.between(date1Instant, date2Instant);
    return getMinutesSecondsString(context, seconds);
}

这篇关于早期Android中Java 8之前的ZonedDateTime到Date的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 18:57