以毫秒为单位的时差问题 [英] Issue with time differences in ms

查看:86
本文介绍了以毫秒为单位的时差问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我显示通知,其中包含我的应用的上次打开日期

In my app, I am displaying Notification with last opened date of my application.

这是我获取上次打开时间的代码,

This is my code for getting last opened time,

long time = 0;
if (MainPageActivity.SettingsInfo != null)
     time = System.currentTimeMillis() - MainPageActivity.SettingsInfo.getLong("LASTOPEN", 0);

求和,

 String getTime(long ms)
    {
        final int SECOND = 1000;
        final int MINUTE = 60 * SECOND;
        final int HOUR = 60 * MINUTE;
        final int DAY = 24 * HOUR;
        String text;
        if (ms > DAY) {
            text=(ms / DAY)+(" Day(s) ago");
        }
        else
            text=(ms / HOUR)+(" Hour(s) ago");

        return text;
    }

工作正常。但是有时它显示0小时前或1250天之前的不相关日期。

我确定SettingsInfo是不为null,并且在运行此代码时具有最后打开的信息。

I am sure that SettingsInfo is not null and has the last opened info when this code runs.

我在上面的代码中使用的是 alarm 。如果差异超过3天,则每天都会显示通知

I am using alarm where I used above code. The notification will be displayed every day if the difference is more than 3 days.

 SettingsInfo.edit().putLong("LASTOPEN", System.currentTimeMillis()).apply();

有人可以解决吗?救救我!

Can anyone solve this? Help me!

推荐答案

您的代码运行正常,您正在 0小时前因为您将 long 除以 int ,并且如果您从上次结束1小时之前打开应用程序
打开,您总是会在0个小时前到达。

Your code is working fine, you are getting 0 Hour(s) ago because you are dividing long by int and if you open your app before 1 hour is completed since last open, you will always get 0 Hour(s) ago.

此外,如@pskink
所指出的,您可以使用 DateUtils.getRelativeTimeSpanString 获取相对时间跨度,例如:

Further, as pointed by @pskink you can use DateUtils.getRelativeTimeSpanString to get relative timespan as:

String getTime(long lastOpen) {
    return DateUtils.getRelativeTimeSpanString(lastOpen, System.currentTimeMillis(), DateUtils.HOUR_IN_MILLIS).toString();
}

lastOpen :存储在<$ c中的时间$ c> MainPageActivity.SettingsInfo.getLong( LASTOPEN,0)

这篇关于以毫秒为单位的时差问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆