gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:59:37 24 4
gpt4 key购买 nike

我想在我的聊天应用程序中显示时间戳,如果消息在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com