在Java中将数字增加20分钟。

huangapple go评论51阅读模式
英文:

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....

在Java中将数字增加20分钟。

答案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(&quot;HH:mm&quot;);
System.out.println(dt.format(df));
for (int i = 0; i &lt; 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 &lt; 24 * 60; min += 20) {
    int next = min + 20;
    String timestamp = String.format(&quot;%02d:%02d - %02d:%02d&quot;, min/60, min%60, next/60, next%60);
    System.out.println(timestamp);
}
/////
00:00 - 00:20
00:20 - 00:40
00:40 - 01:00
...

huangapple
  • 本文由 发表于 2020年5月30日 02:01:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/62092073.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定