Loom :
I am tried to print 30 consecutive dates. The following is my code
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))))
However output does not consecutive:
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
What is the reason of this behavior and how to fix it?
Elliott Frisch :
Your math must overflow somewhere (integer math). Coerce the terms to long
before you begin multiplication (you can append L
) like
(0 to 29).foreach(i => println(sdf.format(new Date(myDate + 24L * 3600 * 1000 * i))))
Or, use TimeUnit.DAYS
which can handle this correctly; something like
import java.util.concurrent.TimeUnit
and then
(0 to 29).foreach(i => println(sdf.format(new Date(myDate + TimeUnit.DAYS.toMillis(i)))))
But, since we're using LocalDate
anyway; it's probably better to write it like
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))))