gpt4 book ai didi

java - 计算关闭时间毫秒到时间

转载 作者:行者123 更新时间:2023-12-02 05:52:29 25 4
gpt4 key购买 nike

下面的代码用于格式化毫秒。计算结果相差甚远。我需要一些帮助。我的代码的输出以及 Date 类中的毫秒数如下。

public static void main(String[] args) {
System.out.println("Wrong Time: " + getTime(999999999 * 599));

}

//Being called into this method is milliseconds = 598999999401
public static String getTime(long miliseconds) {
int years = (int) ((miliseconds / (1000*60*60*24*7*52*12)));
int months = (int) (miliseconds / (1000*60*60*24*7*52) % 12);
int weeks = (int) ((miliseconds / (1000*60*60*24*7)) % 52);
int days = (int) ((miliseconds / (1000*60*60*24)) % 7);
int hours = (int) ((miliseconds / (1000*60*60)) % 24);
int minutes = (int) ((miliseconds / (1000*60)) % 60);
int seconds = (int) (miliseconds / 1000) % 60;
Date date = new Date(598999999401L);//This gets the real time
System.out.println("Right Time: " + date.getYear() + " years " + (int)(date.getMonth() % 12) + " months " + (int)(date.getDay() % 52) + " weeks "
+ (int)(date.getDay() % 7) + " days " + (int)(date.getHours() % 24) + " hours " + (int)(date.getMinutes() % 60) + " minutes " +
+ (int)(date.getSeconds() % 60) + " seconds");
return (years <= 0 ? "" : years + " year" + (years != 1 ? "s" : "")) +
(months <= 0 ? "" : " " + months + " month" + (months != 1 ? "s" : "")) +
(weeks <= 0 ? "" : " " + weeks + " week" + (weeks != 1 ? "s" : "")) +
(days <= 0 ? "" : " " + days + " day" + (days != 1 ? "s" : "")) +
(hours <= 0 ? "" : " " + hours + " hour" + (hours != 1 ? "s" : "")) +
(minutes <= 0 ? "" : " " + minutes + " minute" + (minutes != 1 ? "s" : "")) +
(seconds <= 0 ? "" : " " + seconds + " second" + (seconds != 1 ? "s" : ""));
}

正确输出(日期类)

Right Time: 88 years 11 months 6 weeks 6 days 14 hours 53 minutes 19 seconds

错误的输出(我的方法)

Wrong Time:  1 month 3 weeks 2 days 3 hours 25 minutes 45 seconds

更新 1(新计算)(仍有逻辑错误):

int years = (int) ((miliseconds / (1000*60*60*24*7*4*12)));
int months = (int) (miliseconds / (1000*60*60*24*7*4) % 12);
int weeks = (int) ((miliseconds / (1000*60*60*24*7)) % 4);
int days = (int) ((miliseconds / (1000*60*60*24)) % 7);
int hours = (int) ((miliseconds / (1000*60*60)) % 24);
int minutes = (int) ((miliseconds / (1000*60)) % 60);
int seconds = (int) (miliseconds / 1000) % 60;

最佳答案

两个问题。

您的代码似乎反射(reflect)了一个月有 52 周的信念。这是有问题的两条线。

int years = (int) ((miliseconds / (1000*60*60*24*7*52*12)));
int months = (int) (miliseconds / (1000*60*60*24*7*52) % 12);

此外,您在应该使用 long 的地方使用了 intint 的最大毫秒数不到 25 天,因此您永远无法使用 int 进行日期/时间算术。

关于java - 计算关闭时间毫秒到时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23419971/

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