scala中java.util.Date不一致的增量

Loo*_*oom 2 java datetime scala

我试图连续打印30个日期.以下是我的代码

val myDate: Long = LocalDate.parse("2017-07-01").atStartOfDay()
  .toInstant(ZoneOffset.of("+0")).getEpochSecond * 1000
val sdf: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd")

(0 to 29).foreach(i => println(sdf.format(new Date(myDate + 24 * 3600 * 1000 * i))))
Run Code Online (Sandbox Code Playgroud)

但输出不连续:

2017-07-01
2017-07-02
2017-07-03
2017-07-04
2017-07-05
2017-07-06
2017-07-07
2017-07-08
2017-07-09
2017-07-10
2017-07-11
2017-07-12
2017-07-13
2017-07-14
2017-07-15
2017-07-16
2017-07-17
2017-07-18
2017-07-19
2017-07-20
2017-07-21
2017-07-22
2017-07-23
2017-07-24
2017-07-25
2017-06-06 <--- !!!!!!
2017-06-07
2017-06-08
2017-06-09
2017-06-10
Run Code Online (Sandbox Code Playgroud)

这种行为的原因是什么以及如何解决?

Ell*_*sch 6

你的数学必须在某处溢出(整数学).long在开始乘法(你可以追加L)之前强制使用这些术语

(0 to 29).foreach(i => println(sdf.format(new Date(myDate + 24L * 3600 * 1000 * i))))
Run Code Online (Sandbox Code Playgroud)

或者,使用TimeUnit.DAYS哪个可以正确处理; 就像是

import java.util.concurrent.TimeUnit
Run Code Online (Sandbox Code Playgroud)

然后

(0 to 29).foreach(i => println(sdf.format(new Date(myDate + TimeUnit.DAYS.toMillis(i)))))
Run Code Online (Sandbox Code Playgroud)

但是,因为我们正在使用LocalDate; 写它可能更好

import java.time.{Instant, LocalDate, ZoneOffset}
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit

val dtf: DateTimeFormatter = DateTimeFormatter.ISO_DATE
val ld: LocalDate = LocalDate.parse("2017-07-01")
(0 to 29).foreach(i => println(dtf.format(ld.plusDays(i))))
Run Code Online (Sandbox Code Playgroud)