gpt4 book ai didi

android - 如何从给定的 unix 时间戳获取到现在为止耗时

转载 作者:行者123 更新时间:2023-11-30 03:26:38 26 4
gpt4 key购买 nike

我得到了一个 unix 时间戳,我需要通过与当前时间比较来找出秒/分钟/小时的差异。我需要这样的东西:

34 sec ago
1 min ago
4 mins ago
5 hours ago
1 days ago
2 days ago

我尝试了一些糟糕的 if-else 风格的代码,但它给出了错误的奇怪输出

String time = null;
long quantity = 0;
long addition = 0;
long diffMSec = System.currentTimeMillis() - Long.parseLong(submissionInfo
.get(CommonUtils.KEY_SUBMISSION_TIME)) * 1000L;
diffMSec /= 1000L;
if (diffMSec < 86400L) { // less than one day
if (diffMSec < 3600L) { // less than one hour
if (diffMSec < 60L) { // less than one minute
quantity = diffMSec;
time = "sec ago";
} else { // greater than or equal to one minute
addition = (diffMSec % 60L) > 0 ? 1 : 0;
quantity = (diffMSec / 60L) + addition;
if (quantity > 1)
time = "mins ago";
else
time = "min ago";
}
} else { // greater than or equal to one hour
addition = (diffMSec % 3600L) > 0 ? 1 : 0;
quantity = (diffMSec / 3600L) + addition;
if (quantity > 1)
time = "hours ago";
else
time = "hour ago";
}
} else { // greater than or equal to one day
addition = (diffMSec % 86400) > 0 ? 1 : 0;
quantity = (diffMSec / 86400) + addition;
if (quantity > 1)
time = "days ago";
else
time = "1 day ago";
}
time = quantity + " " + time;

我需要一些具有更智能方法的工作代码,甚至需要任何具有工作解决方案的方法。帮我弄清楚。

最佳答案

我认为你应该使用 Calendar

Calendar cal = Calendar.getInstance();

String time = "yourtimestamp";
long timestampLong = Long.parseLong(time)*1000;
Date d = new Date(timestampLong);
Calendar c = Calendar.getInstance();
c.setTime(d);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);

Calendar 实现 Comparable 所以 ...

long subs = Math.abs(cal.getTimeInMillis()  c.getTimeInMillis());
Calendar subCalendar = (Calendar)cal.clone();
subCalendar.setTimeInMillis(subs);

您还可以使用 this link, because it seems to be a problem like yours

关于android - 如何从给定的 unix 时间戳获取到现在为止耗时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18120236/

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