Aliaksandr Kazlou
Aliaksandr Kazlou

Reputation: 3301

Why parsing date in clojure shifts the result 2 hours back

Clojure code

(def fmt (java.text.SimpleDateFormat. "yyyy-MM-dd"))
#'user/fmt
user=> (.parse fmt "2015-07-10")
#inst "2015-07-09T22:00:00.000-00:00"

Analogous Java code:

public class DateFmt {
    public static void main(String[] args) throws ParseException {
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        final Date date = sdf.parse("2015-07-10");

        System.out.println(date);
    }
}

While Java code prints: Fri Jul 10 00:00:00 CEST 2015 (which is what I expect), but Clojure shifts 2 hours back?

Upvotes: 1

Views: 454

Answers (1)

Makoto
Makoto

Reputation: 106390

There's a difference between Clojure's instant and Java's Date, the big piece being that the time offset is optional.

Unlike RFC3339:

  • we only parse the timestamp format
  • timestamp can elide trailing components
  • time-offset is optional (defaults to +00:00)

So, Clojure's time is always tied to UTC, whereas Java is tied to what your local timezone is.

The times are actually equivalent, since you're two hours ahead of UTC.

If you want Clojure output to match Java, then you have to instruct the SimpleDateFormat instance to read the time in as UTC instead.

(def fmt
  (let [format (java.text.SimpleDateFormat. "yyyy-MM-dd")]
    (.setTimeZone format (java.util.TimeZone/getTimeZone "UTC"))
    format))

Upvotes: 6

Related Questions