java - How to calculate relative time spans using Java (code converting problem)?
问题描述
I decided to give myself a challenge on Java that implements this question's achievement.
The things I have to do is get LocalDateTime
, convert the same code from the linked question's answers, then receiving a string from the function.
Here's what I've done so far:
public static String relTime(LocalDateTime now)
{
// accepted answer converted to Java
const int min = 60 * SECOND;
const int hour = 60 * MINUTE;
const int day = 24 * HOUR;
const int mon = 30 * DAY;
// still don't know how to convert this method
var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);
double delta = Math.Abs(ts.TotalSeconds);
if (delta < 1 * MINUTE)
return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
if (delta < 2 * MINUTE)
return "a minute ago";
if (delta < 45 * MINUTE)
return ts.Minutes + " minutes ago";
if (delta < 90 * MINUTE)
return "an hour ago";
if (delta < 24 * HOUR)
return ts.Hours + " hours ago";
if (delta < 48 * HOUR)
return "yesterday";
if (delta < 30 * DAY)
return ts.Days + " days ago";
if (delta < 12 * MONTH)
{
int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
return months <= 1 ? "one month ago" : months + " months ago";
}
else
{
int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
return years <= 1 ? "one year ago" : years + " years ago";
}
}
The only problem that I should encounter is from var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);
.
Although I read 2 questions from Stack Overflow finding equivalents of TimeSpan
and Ticks
, I baely have any ideas how to properly convert the line of code. Also, I have to get a double
which will need math.abs()
to get TotalSeconds
which I can't really find a proper way to deal with either, but I did find ZoneOffset.ofTotalSeconds
and still don't know how to deal with it.
So how can I convert this properly?
var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);
double delta = Math.Abs(ts.TotalSeconds);
解决方案
You could use SimpleDateFormat to create a nice display format (use something like "HH hours, mm minutes and ss seconds ago"
for the format (not sure if this exact example works)). You could also use Instant to get the current time, and you can use Instant.now().minusSeconds(Instant.now().minusSeconds(seconds).getEpochSeconds())
for the time difference (or just use System.currentTimeMillis() and multiply by 1000).
Alternatively, you could use Duration and write a custom display format using getSeconds() and getHours() etc.
推荐阅读
- python - Pygame-同时旋转精灵并跟随路径
- excel - 如何检查一个值是否在数组的多个维度中
- python - 导入模块时如何解决 NameError 或 ModuleNotFound 错误?
- ios - 如何正确启动 iPhone 摄像头
- php - 我无法将 Bootstrap 4.1.0 链接到我的 Laravel 项目
- python - Python,输入字符串并获取输出的脚本
- angular - 尝试在 android (ionic v4) 上下载图像时出错
- javascript - 如何堆叠两个可滚动的 div
- python - 为什么当 x 在 numpy 中增加时,2 提高到 x 会给出负值?
- reactjs - 将 Jest 和 Enzyme 添加到 React 样板文件中