4

I'm confused on usage of the clojure.java-time library usage that wraps Java 8's java.time api.

I want a function that translates a date in string format from "yyyy-MM-dd'T'HH:mm:ss" format to "MM/dd/YYYY hh:mm:ss a" format.

Here's my function:


(require '[java-time :as jt])

(defn change-ds-format [in-ds]
  {:pre [string? in-ds ]}
  (let [input-format "yyyy-MM-dd'T'HH:mm:ss"  
        output-format "MM/dd/YYYY hh:mm:ss a"]
    (->> in-ds
         (jt/local-date-time input-format)
         (jt/format output-format)))) 

This looks ok:

(change-ds-format "2019-12-28T00:00:00" )
;=> "12/28/2019 12:00:00 AM"

I have no idea why this is pushed to 2020?

(change-ds-format "2019-12-29T00:00:00" )
;=> "12/29/2020 12:00:00 AM"
;; Why is this one 2020 ???

I thought maybe it was a timezone offset issue but there is no way it should be shifting to the year 2020 I don't believe.

joefromct
  • 1,506
  • 13
  • 33
  • By the way, your first format "yyyy-MM-dd'T'HH:mm:ss" (standard [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format) is used by default by the `LocalDateTime` class. No need to specify a formatting pattern explicitly. In Java syntax, `LocalDateTime.parse( "2019-12-29T00:00:00" )`. – Basil Bourque Dec 18 '19 at 08:31
  • Does this answer your question? [Y returns 2012 while y returns 2011 in SimpleDateFormat](https://stackoverflow.com/questions/8686331/y-returns-2012-while-y-returns-2011-in-simpledateformat) Or this? [Why does Java's java.time.format.DateTimeFormatter#format(LocalDateTime) add a year?](https://stackoverflow.com/questions/34521733/why-does-javas-java-time-format-datetimeformatterformatlocaldatetime-add-a-y) – Ole V.V. Dec 18 '19 at 17:02

1 Answers1

6

Because yyyy is not YYYY

From Oracle docs for DateTimeFormatter:

 ... snip...
u       year                        year              2004; 04
y       year-of-era                 year              2004; 04
...snip...
Y       week-based-year             year              1996; 96
w       week-of-week-based-year     number            27
...snip...

I'm not very proficient at datetime arithmetic or the nuances but I believe that in week-based year counting this December's 30th and 31st are counted as year 2020 because these dates belong to week #1, not week #52 or #53.

mike3996
  • 17,047
  • 9
  • 64
  • 80