gpt4 book ai didi

java - 向下舍入时间至最后 5 分钟

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

我想在代码中舍入到最后 5 分钟,但它不起作用:

Date whateverDateYouWant = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(whateverDateYouWant);
int unroundedMinutes = calendar.get(Calendar.MINUTE);
int mod = unroundedMinutes % 5;
calendar.add(Calendar.MINUTE, -(mod < 3 ? -mod : (5-mod)));
SimpleDateFormat format1 = new SimpleDateFormat("dd.MM.yyyy HH:mm");
String formattedDate = format1.format(calendar.getTime());

因此,如果是 08:16,则应为 08:15;如果是 09:49,则应为 09:45;如果是 12:00,则应向下舍入为 11:55。

最佳答案

替换这一行:

calendar.add(Calendar.MINUTE, -(mod < 3 ? -mod : (5-mod)));

这样:

calendar.add(Calendar.MINUTE, unroundedMinutes == 0 ? -5 : -mod);

关于java - 向下舍入时间至最后 5 分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24108642/

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