gpt4 book ai didi

java - 计算两个日期之间的差异: not working as expected

转载 作者:行者123 更新时间:2023-12-01 23:09:56 25 4
gpt4 key购买 nike

这是我的代码:

public enum MILLI_CONVERSIONS {
//values in milliseconds
SECOND(1000),
MINUTE(1000*60),
HOUR(1000*60*60),
DAY(1000*60*60*24),
WEEK(1000*60*60*24*7),
MONTH(1000*60*60*24*30),
YEAR(1000*60*60*24*31*12);

private final long millis;

private MILLI_CONVERSIONS(final long millis) {
this.millis = millis;
}

public long getMillis() {
return millis;
}
}

public static String getDateDifferenceFromToday(Date startDate){
Date today = new Date();
long delta = today.getTime() - startDate.getTime();

Integer diff;
String diffText = "";
//seconds
if (delta < MILLI_CONVERSIONS.MINUTE.getMillis()){
diff = Integer.valueOf((int) (delta/MILLI_CONVERSIONS.SECOND.getMillis()));
diffText = diff.toString() + " seconds ago";
}
//minutes
else if (delta < MILLI_CONVERSIONS.HOUR.getMillis()){
diff = Integer.valueOf((int) (delta/MILLI_CONVERSIONS.MINUTE.getMillis()));
diffText = diff.toString() + " minutes ago";
}
//hours
else if (delta < MILLI_CONVERSIONS.DAY.getMillis()){
diff = Integer.valueOf((int) (delta/MILLI_CONVERSIONS.HOUR.getMillis()));
diffText = diff.toString() + " hours ago";
}
//days
else if (delta < MILLI_CONVERSIONS.WEEK.getMillis()){
diff = Integer.valueOf((int) (delta/MILLI_CONVERSIONS.DAY.getMillis()));
diffText = diff.toString() + " days ago";
}
// weeks
else if(delta < MILLI_CONVERSIONS.MONTH.getMillis()){
diff = Integer.valueOf((int) (delta/MILLI_CONVERSIONS.WEEK.getMillis()));
diffText = diff.toString() + " weeks ago";
}
// months
else if(delta < MILLI_CONVERSIONS.YEAR.getMillis()){
diff = Integer.valueOf((int) (delta/MILLI_CONVERSIONS.MONTH.getMillis()));
diffText = diff.toString() + " months ago";
}
// years
else{
diff = Integer.valueOf((int) (delta/MILLI_CONVERSIONS.YEAR.getMillis()));
diffText = diff.toString() + " years ago";
}

return diffText;
}

在我几周之前它似乎工作得很好。即使距离一周,也会显示 0 个月。然后当它是月份时,它似乎得到了正确的月份数,但它显示“几年前”(例如,如果是两个月前,而不是“2个月前”,它会说“2年前”。永远不会达到年份,它只会持续几个月(例如,如果是 16 个月前,它应该说“1 年前”,但它说“16 年前”)。

我正在我的 Android 应用程序中使用此功能,因此如果有任何库可以执行此操作,或者我缺少一些内置方法来计算此功能,请告诉我。

谢谢。

最佳答案

当您定义枚举常量时,您需要使用长整数进行计算,因为您会溢出整数范围。例如使用

YEAR(1000L*60*60*24*31*12)

而不是

YEAR(1000*60*60*24*31*12)

将第一个数字指定为 long 就足以以 long 数据类型执行计算。

关于java - 计算两个日期之间的差异: not working as expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22176712/

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