Hi,
I am just starting to learn Clojure by writing a small library. I came
across a situation in which I have to parse a String for getting a Date. Now
the string can be in one of the three formats. So I wrote this functions to
parse it:

(def #^{:private true :tag SimpleDateFormat} full-date-format
  (doto (SimpleDateFormat. "EEE, dd MMMM yyyy HH:mm:ss +0000")
    (.setTimeZone (TimeZone/getTimeZone "GMT"))))

(def #^{:private true :tag SimpleDateFormat} date-format-wo-tz
  (doto (SimpleDateFormat. "EEE, dd MMMM yyyy HH:mm:ss")
    (.setTimeZone (TimeZone/getTimeZone "GMT"))))

(def #^{:private true :tag SimpleDateFormat} short-date-format-wo-tz
  (doto (SimpleDateFormat. "dd MMM yyyy, HH:mm")
    (.setTimeZone (TimeZone/getTimeZone "GMT"))))

(defn- parse-date [date-str]
  (if (some #(% date-str) [nil? blank?])
    nil
    (let [clean-date-str (trim date-str)]
      (try
        (.parse full-date-format clean-date-str)
        (catch java.text.ParseException e
          (try
            (.parse date-format-wo-tz clean-date-str)
            (catch java.text.ParseException e
              (.parse short-date-format-wo-tz clean-date-str))))))))

I can't help but think that there must be a better way to do the same
without so many nested try catch blocks. If this were Java, I could have
looped over all the date formats and used an explicit return in the try
block and continue in catch block. I don't understand how to do explicit
return in Clojure.

Also as the number of formats grows, I'll have to add more nested try catch
blocks. Please suggest a cleaner way to do this.

Regards,
Abhinav

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to