gpt4 book ai didi

java - 计算已经过去了多长时间 Date java

转载 作者:太空狗 更新时间:2023-10-29 16:13:50 25 4
gpt4 key购买 nike

我有一个函数:

  public String getTimePast(Date d) {
//insertcodehere
}

接受消息的日期,并且必须以特定格式返回基于当前时间过去了多少时间。例如,如果它刚刚发布,它会说“现在”

如果已经过了 4 分钟,它会说“4min”如果已经 23 小时,它将显示“23 小时”等等

以下是我如何在没有运气的情况下尝试做到这一点!我怎么能做到这一点?谢谢!

public String getTimePast(Date d) {


Calendar c = Calendar.getInstance();

int hr = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);


if (year == d.getYear()) {
if (month == d.getMonth()) {
if (day == d.getDay()) {
if (hr == d.getHours()) {
if (min == d.getMinutes()) {
return "Now";
} else {
return min - d.getMinutes() + "m";
}
} else {
return hr - d.getHours() + "hr";

}
} else {
return day - d.getDay() + "d";
}
} else {
return month - d.getMonth() + "m";
}
} else {
return year - d.getYear() + "y";
}


}

最佳答案

如何使用另一个日历对象来简单地找出差异

Calendar now = Calendar.getInstance();
Calendar start = Calendar.getInstance();
start.setTime (d);

long milliseconds1 = start.getTimeInMillis();
long milliseconds2 = now.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("\nThe Date Different Example");
System.out.println("Time in milliseconds: " + diff
+ " milliseconds.");
System.out.println("Time in seconds: " + diffSeconds
+ " seconds.");
System.out.println("Time in minutes: " + diffMinutes
+ " minutes.");
System.out.println("Time in hours: " + diffHours
+ " hours.");
System.out.println("Time in days: " + diffDays
+ " days.");
}

参见 http://www.roseindia.net/java/beginners/DateDifferent.shtml

关于java - 计算已经过去了多长时间 Date java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35422282/

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