Getting the time in terms of hours and minutes in cljc

What’s the best way to write a function in a cljc file that returns the time as hours and minutes?

I see a lot of online things talking about clj-time and how JodaTime is now deprecated.

I’d like to avoid external libraries as much as possible. And I assume for cljs I can use (-> (js/Date.) .getHours) so ideally I want to write :

(defn get-hours [] #?(
   :cljs (-> (js/Date.) .getHours)
   :clj (WHAT GOES HERE?)
))

What goes in the WHAT GOES HERE? slot?

(import '(java.util Calendar))

(.get (Calendar/getInstance) Calendar/HOUR_OF_DAY)
1 Like

Or (-> (java.time.ZonedDateTime/now) .getHour) though there may be different time semantics between the two platforms that you may or may not want to reconcile.

3 Likes

Just realize that the hours you will get back depends on the time zone.

For example, it can be 7pm in one part of the world and 10pm in another.

Be careful when using time, if you don’t specify a timezone in your case, for both JS and Java, what timezone will their respective runtime default too? It’s a mystery…

Especially the logic to get a default time zone might differ between one browser to another and from what the Java VM will do.

Just an FYI.

P.S.: I would also personally lean on the java.time APIs, it’s the newer time API in Java, the Calendar/Date stuff in java.util is very old, and while it also works fine, they’ve become a bit out of fashion.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.