英文:
Adding 20 minutes to number in java
问题
所以我需要一个变量以24小时制显示时间(01:00, 09:00),每次循环时都要将时间增加20分钟。然后我需要在字符串中使用这个值。
时间需要从任意给定的时间开始,比如00:00。
有任何想法怎么做吗?
输出应该像这样:00:00-00:20,00:20-00:40,00:40-01:00,依此类推...
英文:
So I need a variable that shows times in 24HR format (01:00, 09:00) and every time I loop through it, to add 20 mins to the time? I then need to use this value in a string.
The time needs to start at any given time. like 00:00
Any ideas how should I go with it?
and output like this 00:00-00:20,00:20-..00:40,00:40-01:00 and so on....
答案1
得分: 1
这段代码将以 HH:mm
格式打印每隔 20 分钟的时间戳:
LocalDateTime dt = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS);
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm");
System.out.println(dt.format(df));
for (int i = 0; i < 24 * 3; i++) {
dt = dt.plusMinutes(20);
System.out.println(dt.format(df));
}
其输出结果如下:
00:00
00:20
00:40
01:00
01:20
...
更新
抱歉,可以通过简单的循环来完成:
for (int min = 0; min < 24 * 60; min += 20) {
int next = min + 20;
String timestamp = String.format("%02d:%02d - %02d:%02d", min/60, min%60, next/60, next%60);
System.out.println(timestamp);
}
/////
00:00 - 00:20
00:20 - 00:40
00:40 - 01:00
...
英文:
This code will print timestamps in HH:mm
format for each 20 minutes:
LocalDateTime dt = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS);
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm");
System.out.println(dt.format(df));
for (int i = 0; i < 24 * 3; i++) {
dt = dt.plusMinutes(20);
System.out.println(dt.format(df));
}
Its output is as follows:
00:00
00:20
00:40
01:00
01:20
...
Update
Sorry, it could be done with simple loop:
for (int min = 0; min < 24 * 60; min += 20) {
int next = min + 20;
String timestamp = String.format("%02d:%02d - %02d:%02d", min/60, min%60, next/60, next%60);
System.out.println(timestamp);
}
/////
00:00 - 00:20
00:20 - 00:40
00:40 - 01:00
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论