我目前正在尝试将长时间转换为剩余时间。我有一个
long remaining = XXXX
长到某个特定日期的毫秒数。例如:3,600,000应该导致int周= 0,天= 0,小时= 1,分钟= 0,秒= 0 我怎么能把它转换成这么久才能得到5个整数:
int weeks;
int days;
int hours;
int minutes;
int seconds;
提前谢谢!
DirtyDev
答案 0 :(得分:2)
首先,我建议将秒数,分钟,小时等中的ms数定义为常数
static final int SECOND = 1000; // no. of ms in a second
static final int MINUTE = SECOND * 60; // no. of ms in a minute
static final int HOUR = MINUTE * 60; // no. of ms in an hour
static final int DAY = HOUR * 24; // no. of ms in a day
static final int WEEK = DAY * 7; // no. of ms in a week
然后,您可以使用基本划分(/
)和模数(%
)操作来找到您需要的内容。
long remaining = XXXX;
int weeks = (int)( remaining / WEEK);
int days = (int)((remaining % WEEK) / DAY);
int hours = (int)((remaining % DAY) / HOUR);
int minutes = (int)((remaining % HOUR) / MINUTE);
int seconds = (int)((remaining % MINUTE) / SECOND);
答案 1 :(得分:2)
对不起,我不想批评太多,我仍然从其他答案中得知,很容易编写难以阅读的代码或编写错误结果的拼写错误代码。 DirtyDev,我知道您可能不被允许使用Duration
,但是对于其他任何人:
long remaining = 3_600_000;
Duration remainingTime = Duration.ofMillis(remaining);
long days = remainingTime.toDays();
remainingTime = remainingTime.minusDays(days);
long weeks = days / 7;
days %= 7; // or if you prefer, days = days % 7;
long hours = remainingTime.toHours();
remainingTime = remainingTime.minusHours(hours);
long minutes = remainingTime.toMinutes();
remainingTime = remainingTime.minusMinutes(minutes);
long seconds = remainingTime.getSeconds();
System.out.println("" + weeks + " weeks " + days + " days "
+ hours + " hours " + minutes + " minutes " + seconds + " seconds");
打印:
0 weeks 0 days 1 hours 0 minutes 0 seconds
它并不完美,但我相信它既可读又正确且强大。 Duration
的意思是从几小时到几纳秒,所以我们仍然需要“手工”做几周。
新年快乐。
答案 2 :(得分:1)
这应该做你想要的。
long inputTimeInMilliseconds = 93800000;
long milliseconds = inputTimeInMilliseconds % 1000;
long seconds = (inputTimeInMilliseconds / 1000) % 60 ;
long minutes = ((inputTimeInMilliseconds / (1000*60)) % 60);
long hours = ((inputTimeInMilliseconds / (1000*60*60)) % 24);
long days = ((inputTimeInMilliseconds / (1000*60*60*24)) % 7);
long weeks = (inputTimeInMilliseconds / (1000*60*60*24*7));
String remainingTime = "time:"+weeks+":"+days+":"+ hours+":"+minutes+":"+seconds+":"+milliseconds;
System.out.println(remainingTime);