Dirk Bergmann

Developer, panographer. Does consultancy work from own company. Lives in Chiang Mai, Thailand.

Twitter

Chiang Mai

Hua Hin

Thailand Hotels

ListVote - List. Vote. Learn.

Partnerseek - Find Partners

Date Formats in Clojurescript

Formatting dates in JavaScript can be tricky, even getting the name of the month. It's possible to use the clunky $.datepicker.formatDate (); from jquery.ui, but in Clojurescript we have the Google Clojure library at our disposal. Its goog.i18n.DateTimeFormat class has a few useful functions that can be applied like so:

(ns netsupply.client.calendars
  (:require 
     [goog.i18n.DateTimeFormat :as dtf]
))

(def format-map
  (let [f goog.i18n.DateTimeFormat.Format]
{:FULL_DATE (.-FULL_DATE f)
:FULL_DATETIME (.-FULL_DATETIME f)
:FULL_TIME (.-FULL_TIME f)
:LONG_DATE (.-LONG_DATE f)
:LONG_DATETIME (.-LONG_DATETIME f)
:LONG_TIME (.-LONG_TIME f)
:MEDIUM_DATE (.-MEDIUM_DATE f)
:MEDIUM_DATETIME (.-MEDIUM_DATETIME f)
:MEDIUM_TIME (.-MEDIUM_TIME f)
:SHORT_DATE (.-SHORT_DATE f)
:SHORT_DATETIME (.-SHORT_DATETIME f)
 :SHORT_TIME (.-SHORT_TIME f)}))

(defn format-date-generic
  "Format a date using either the built-in goog.i18n.DateTimeFormat.Format enum
or a formatting string like \"dd MMMM yyyy\""
  [date-format date]
  (.format (goog.i18n.DateTimeFormat.
            (or (date-format format-map) date-format))
           (js/Date. date)))

Example usage:

(format-date-generic :LONG_DATE (js/Date.)) > "July 14, 2012"
(format-date-generic "dd MMMM yyyy" (js/Date.)) > "14 July 2012"
(format-date-generic "MMMM" (js/Date.)) > "July"

Ah, there's the name of the month!