2

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?

1
  • 5
    int math overflow: 24 * 3600 * 1000 * 25 = -2134967296. You need to force long math. Commented Aug 3, 2018 at 2:28

2 Answers 2

6

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))))
Sign up to request clarification or add additional context in comments.

2 Comments

"Prefer TimeUnit.DAYS"??? Wouldn't your preference be to stay way, waayyy clear of SimpleDateFormat if you have LocalDate support (see line 1 of question code)? Because even your code will produce incorrect result when it crosses Daylight Savings Time.
You're right about int math overflow: 24 * 3600 * 1000 * 25 = -2134967296
1

Such a simple task really doesn't need such complicated calculations.

import java.time.LocalDate
import java.time.temporal.ChronoUnit.DAYS

Seq.iterate(LocalDate.parse("2017-07-01"), 30)(DAYS.addTo(_, 1))
   .foreach(println)

1 Comment

Deserves a symbolic extension method! Maybe +@ for plus days.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.