java - 如何为像谷歌信使这样的聊天应用程序制作时间戳

标签 java android

我想在我的聊天应用程序中显示时间戳,如果消息在 2 分钟前发送,则更新此时间戳以在时间戳中显示 2 分钟前我使用此方法在发送消息时显示时间戳,但我想每秒更新一次

Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
timeStamp = simpleDateFormat.format(calendar.getTime());

最佳答案

您必须使用过 ListView 或 RecyclerView,只需在适配器中使用以下方法即可在 View 中设置时间。

注意:当调用此方法时,这将为您提供更新的时间,如果您的用户不断上下滚动,您将获得最新的更新时间,如果用户在这种情况下不滚动,则会获得最新的更新时间。不会给您最晚时间。

/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

private static final int SECOND_MILLIS = 1000;
private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;
private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS;
private static final int DAY_MILLIS = 24 * HOUR_MILLIS;


public static String getTimeAgo(long time, Context ctx) {
    if (time < 1000000000000L) {
        // if timestamp given in seconds, convert to millis
        time *= 1000;
    }

    long now = getCurrentTime(ctx);
    if (time > now || time <= 0) {
        return null;
    }

    // TODO: localize
    final long diff = now - time;
    if (diff < MINUTE_MILLIS) {
        return MINUTE_MILLIS/SECOND_MILLIS;
    } else if (diff < 2 * MINUTE_MILLIS) {
        return "a minute ago";
    } else if (diff < 50 * MINUTE_MILLIS) {
        return diff / MINUTE_MILLIS + " minutes ago";
    } else if (diff < 90 * MINUTE_MILLIS) {
        return "an hour ago";
    } else if (diff < 24 * HOUR_MILLIS) {
        return diff / HOUR_MILLIS + " hours ago";
    } else if (diff < 48 * HOUR_MILLIS) {
        return "yesterday";
    } else {
        return diff / DAY_MILLIS + " days ago";
    }
}


使用 DateUtils's 之一getRelative* 按照 Sangharsh 的建议运行。

关于java - 如何为像谷歌信使这样的聊天应用程序制作时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42068508/

相关文章:

Android 如何只能在 mediaPlayer 中播放歌曲 30 秒

java - 无法发布通知 channel 空日志?

c# - 类似于 C# 的 Java SimpleDateFormat

java - 如何将 Java Deque<T> 转换为 DefaultListModel?

java - 带有倒数计时器的 ProgressBar - Android

Android获取图库图片Uri路径

java - Java 比较 2 个字符串的回文检查

java - R.java 没有 R.id.map 的 map

android - 尝试在运行 4.2 的设备上访问 Picasa 图像时出现安全异常

android - 来自运行 Android 的三星设备的序列号