在过去的几天里,我尝试了最后一次在android中看到的功能,以便让人们活跃起来....我研究了许多答案,但我不满意...... 这是代码,将找到否。几天或几周或几年前这个人在线的人数...... 对于每个新的android编码器来说,这只是一块蛋糕......
GetTimeAgo getTimeAgo = new GetTimeAgo();
long lastTime = Long.parseLong(online);
String lastSeenTime = getTimeAgo.getTimeAgo(lastTime, getApplicationContext());
mLastSeenView.setText(lastSeenTime);
通过上面的代码,你可以将它应用于任何活动......
打开.class文件GetTimeAgo 并应用以下代码...
public class GetTimeAgo extends Application {
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 double DAY_MILLIS = 24 * HOUR_MILLIS;
private static final double WEEK_MILLIS = 7 * DAY_MILLIS;
private static final double MONTH_MILLIS = DAY_MILLIS * 30;
private static final double YEAR_MILLIS = WEEK_MILLIS * 52;
public static String getTimeAgo(long time, Context ctx) {
if (time < 1000000000000L) {
// if timestamp given in seconds, convert to millis
time *= 1000;
}
long now = System.currentTimeMillis();
if (time > now || time <= 0) {
return null;
}
// TODO: localize
final long diff = now - time;
if (diff < MINUTE_MILLIS)
{
return "just now";
}
else if (diff < 2 * MINUTE_MILLIS)
{
return "a minute ago";
}
else if (diff < 50 * MINUTE_MILLIS)
{
double roundup = diff / MINUTE_MILLIS;
int b = (int)(roundup);
return b + " minutes ago";
}
else if (diff < 90 * MINUTE_MILLIS)
{
return "an hour ago";
}
else if (diff < 24 * HOUR_MILLIS)
{
double roundup = diff / HOUR_MILLIS;
int b = (int)(roundup);
return b + " hours ago";
}
else if (diff < 48 * HOUR_MILLIS)
{
return "yesterday";
}
else if (diff < 7 * DAY_MILLIS)
{
double roundup = diff / DAY_MILLIS;
int b = (int)(roundup);
return b + " days ago";
}
else if (diff < 2 * WEEK_MILLIS)
{
return "a week ago";
}
else if (diff < DAY_MILLIS * 30.43675)
{
double roundup = diff / WEEK_MILLIS;
int b = (int)(roundup);
return b + " weeks ago";
}
else if (diff < 2 * MONTH_MILLIS)
{
return "a month ago";
}
else if (diff < WEEK_MILLIS * 52.2)
{
double roundup = diff / MONTH_MILLIS;
int b = (int)(roundup);
return b + " months ago";
}
else if(diff < 2 * YEAR_MILLIS)
{
return "a year ago";
}
else
{
double roundup = diff / YEAR_MILLIS;
int b = (int)(roundup);
return b + " years ago";
}
}
}
如果你有更好的回答plz分享:)
答案 0 :(得分:0)
我不确定你是否想要走这条路,但它可能有效。
如果您在应用中打开实时数据库,则每次打开应用时都可以使用.setValue(value)
设置数据库的日期,其中value
类似于,
//Runs in your main loop
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference lastSeenData = database.getReference("message");
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
lastSeenData.setValue(dateFormate.format(date));
您可能需要在.toString
声明中致电setValue
。
如果你想做类似&#34; So和So最后一次出现在2d之前&#34;,那么你可能必须得到日期So So So登录,然后从当前减去它日期。我的想法是,它更容易获得毫秒,用当前毫秒减去然后将差异作为格式化日期吐出。