Fork me on GitHub

interestingly it works if you wrap (first is) with (boolean (first is)) in the recur, no idea why though.


is there offical clojure way to parse numbers with either euro format "1.222,33" or american style "1,222.33" ?


@christian.gonzalez Yep. I'm curious why the above does not work though. Digging through the source does not make it clear. I did find but it doesn't dig into the why.


The Clojure compiler tries to use primitives for loop 'variables' for better performance. If it does not for a particular loop variable, that one will be any JVM object, which can in many cases lead to allocating a new JVM object for that loop variable on each iteration.


Is that the 'why' part you are wondering about? Or some other aspect of the behavior?


Why does this work? Note the only change is pos? -> true? on the loop first binding.

(defn test-2
  (loop [x? (true? "")
         is (map some? [1 nil 2 nil])]
    (when (not-empty is)
        (first is)
        (rest is)))))


pos? is defined as inline and clojure.lang.Numbers/isPos returns boolean (primitive) but true? is defined in Clojure to return Boolean (object).


user=> (source pos?)
(defn pos?
  "Returns true if num is greater than zero, else false"
   :inline (fn [num] `(. clojure.lang.Numbers (isPos ~num)))
   :added "1.0"}
  [num] (. clojure.lang.Numbers (isPos num)))
user=> (source true?)
(defn true?
  "Returns true if x is the value true, false otherwise."
  {:tag Boolean,
   :added "1.0"
   :static true}
  [x] (clojure.lang.Util/identical x true))


Ah. So then how about this one?

(defn test-2
  (loop [x? (pos? 1)
         is (map some? [1 nil 2 nil])]
    (when (not-empty is)
        ^boolean (first is)
        (rest is)))))
Syntax error (IllegalArgumentException) compiling fn* at (src/foo.clj:3:1).
 recur arg for primitive local: x_QMARK_ is not matching primitive, had: boolean, needed: boolean


Also that unnecessary newline in pos? 😭


Because you can't type hint an expression with a primitive.


That actually "tags" the expression with clojure.core/boolean 🙂


user=> ^boolean []
user=> (meta *1)
{:tag #object[clojure.core$boolean 0xa567e72 "[email protected]"]}


I see. So the only way to get a loop to work if the initial binding is a primitive is to use a predicate that returns a primitive?


(boolean (first is)) works?



(defn test-2
  (loop [x? (pos? 1)
         is (map some? [1 nil 2 nil])]
    (when (not-empty is)
        (boolean 1)
        (rest is)))))
Syntax error (IllegalArgumentException) compiling fn* at (src/foo.clj:3:1).
 recur arg for primitive local: x_QMARK_ is not matching primitive, had: Object, needed: boolean


boolean calls to

static public boolean booleanCast(Object x){
	if(x instanceof Boolean)
		return ((Boolean) x).booleanValue();
	return x != null;
which appears to return a primitive.


user=> (loop [x (pos? 1)] (when-not x (recur (boolean nil))))
user=> (loop [x (pos? 1)] (when-not x (recur (first [false]))))
Syntax error (IllegalArgumentException) compiling fn* at (REPL:1:1).
 recur arg for primitive local: x is not matching primitive, had: Object, needed: boolean
user=> (loop [x (pos? 1)] (when-not x (recur (boolean (first [false])))))


Seems to work for me.


Pass 1 instead of (first …


Right, but you're not passing 1, you're passing (first is) for which it does work.


But yes, (boolean (first ... does work.


Why not (boolean 1)?


Look at the code again and think about it being inlined.


Inline expands to (. clojure.lang.RT (booleanCast 1)) which will hit this branch return x != null; in booleanCast. Why is that returning an object? Forgive me if it’s blatantly obvious, I’m a bit tired but this problem has been nagging at me all evening!


user=> (loop [x (pos? 1)] (when-not x (recur (not= 1 nil))))
Syntax error (IllegalArgumentException) compiling fn* at (REPL:1:1).
 recur arg for primitive local: x is not matching primitive, had: java.lang.Boolean, needed: boolean
user=> (loop [x (pos? 1)] (when-not x (recur (.booleanValue (Boolean. 1)))))
I'm assuming that inlining a function call on a literal value is going to expand parts of it and so you'd get the equivalent of the first one since 1 isn't an instance of Boolean


(although it's happening at a Java level I assume -- I'd have to go digging into the compiler in depth for that)


I'm just not terribly surprised there are weird edge cases like this...


I’m not surprised either… My colleague hit this and I just could not give him a reason why. In all the years I’ve been doing Clojure I haven’t hit this one yet.


inline is weird. Primitive deduction/auto-hinting locals is weird. The combination doubly-so.


I still don’t totally follow how it’d get to not= in Clojure though


I was just simulating the code from the Java method definition.


By way of illustration of what I suspect is happening (since it fits the observed behavior).


But the actual code appears to be returning the primitive unless the JVM itself is doing something.


static public boolean booleanCast does that mean booleanCast will always return a primitive? I’d think so


If it is inlining the bytecode, and potentially optimizing based on knowing it is passed a literal, it's entirely possible it "loses" the primitive return type of the function being inlined in that case.


I'm thinking back to when I used to write compilers and virtual machines (late '80s/early '90s) and that was the sort of optimization we would do, including pre-evaluating parts of inlined functions when the compiler knows the argument is a literal.


Oh, if it’s doing more than what meets the eye here then that seems like a plausible explanation. I’m not very familiar with how inline works other than it being “like a macro.”


Like I say, I'd have to dig deep into the Clojure compiler sources to be sure of exactly what's going on in this case -- but it fits with what I'd expect, based on what I've seen done. I would say that it's a bug that the primitive return type is lost in that pre-evaluation tho'...


I thought that’s where we were landing 🙂 I’m about ready to fall asleep though. Will keep looking into this tomorrow morning. Very curious what is happening!


You should post some of the smaller fragments I showed above into a post on and see if it gets accepted as a bug.


Great idea! I’ll do that tomorrow.


@seancorfield You said “Because you can’t type hint an expression with a primitive” yesterday. Why can’t you type hint an expression with a primitive?


This one is odd…

(loop [x (pos? 1)]
  (when-not x
    (recur (pos? x))))
Syntax error (IllegalArgumentException) compiling fn* at (src/foo.clj:4:1).
 recur arg for primitive local: x is not matching primitive, had: Object, needed: boolean


I showed you why earlier in this thread. When you use boolean or long or double in a "type hint" you are referring to the Clojure.core function


When you have ^x y that expands to ^{:tag x} y and both x and y are evaluated.


^Boolean is fine because Boolean evaluates to java.lang.Boolean -- the class -- but ^boolean evaluates to ^{:tag clojure.core/boolean} and Java primitives aren't classes so it's pretty much impossible to get a reference to them in this case. It's why locals (`let`, loop) are auto-hinted as primitives, because you can't do it yourself.


Auto-hinted when the compiler can. So when it can't you have to apply the hint elsewhere?


Not as far as I know - java covers that pretty well though


so just use the java


if you need to support clojurescript too you'll have to look at npm and see whats available


got it , makes sense @emccue .. and thank goodness I dont need clojurescript


yeah, lmk if you need help with any of the java interop stuff


its pretty simple but it did take some learning for me before i was okay with just jumping to that


i will try it now and see if i get it ( thanks for offering help )


thanks again @emccue I got it working .. for both usa and euro format parsing


I’m exploring the idea of an object-capability structure in an application I’m writing, I’m hoping for some inspiration from anyone who has either done this or thought about it. The obvious transcription from a typical OO implementation is protocols+records but it feels a bit strange and overly difficult in Clojure, maybe some sort of (perform :cap/whatever user-identity ,,,) multimethod could work more naturally but it feels a bit foreign too.


@jonathanj My first reaction would be "Why? What problem are you actually trying to solve here?"


@seancorfield Fair question, so I guess my reasoning is that previous systems I’ve written or worked on (not all necessarily in Clojure) do this kind of authorization checking at the fringes, e.g. the HTTP API, but once you’re past that the whole system is this soft gooey centre where Bad Things can happen accidentally because the rest of the system (the SQL DB, state atoms, etc.) are just code that other code is fully privileged to do with as it pleases. Maybe one solution to that is to sprinkle permission checks around but that often seems to have patchy coverage.


One issue could find with this is: There is perceived security vs real security. Let me explain.


If your aim is to protect each method from some bad code infecting the system, then your solution would not provide real security.


in worst case the bad code would just write/rewrite its own bytecode.


If you're trying to prevent a programming mistake by calling code that a user should never access via a legitimate api call, then it could work.


Yes the former is probably pointless to try prevent, if you have a malicious programmer then there are probably a hundred ways to circumvent this. My concern is more a matter of making it simple to avoid obviously bad behaviour without the complexity of having to consider the cascading effects of your intent at each point.


cool. The java way would be to sprinkle annotations on each method. Which is just metadata in the end, and requires a processor to interpret it.


one idea would be to,annotate functions with a permission.


in clojure via metadata.


and then run the functions in some kind of processor that would check user permissions etc.


e.g (with-user user (call stack ) )


The function would presumably have to check its own metadata, right?


Or just some context to each function and an assertion?

(defn whatevs
  [ctx ...]
  (has-perm! ctx :updating-thingimys))


(sec/defn whatevs ^...perms... [] code.. )


where sec/defn is your own macro checking for e.g *user* or something. that could work


Right. I tried to do this with just defn and realised that the metadata is attached to the var, so trying to write some kind of (perform fn ctx …) wrapper wasn’t working the way I wanted it to.


So that basically boils down to what @cursork said, except the macro implicitly implements the assertion.


But the macro still needs to be fed what the right perm is... Might as well accept the one line of code for making everything explicit


a harder way would be to have the (with-user call any function) intercept all functions with the metadata associated and add the checks as bytecode


@cursork I actually ended up with pretty much that implementation yesterday but it seems like a macro might make it slightly harder to forget to perform the assertion. Just because sec/defn is the first thing you write and then a spec could verify the data, vs calling an assert as the third or fourth step of the implementation. :man-shrugging:


I went looking for a precondition library that didn’t use AssertionError but didn’t come up with much.


👍 JVM world Exceptions are standard for this, and imo not bad.


Well.. we do have pre and post-conditions in Clojure. So it can be:

(defn x [ctx ...] {:pre [(has-perm ctx :xyz)]} #_some-code)


+1 and you could macro it up if you wanted to. I prefer explicit context but ctx could come form a dynamic var.


Thanks for the discussion, helped me get out of my own head a bit and find some inspiration. 🙏

👍 6

I have a weird problem probably related to AOT. In a project I'm factoring out the front-end build and hence I don't need the dependency on ClojureScript anymore. When I remove that dep, I suddently can't require taoensso.carmine anymore:

boot.user=> (require '[taoensso.carmine.commands] :reload-all)
         java.lang.NoClassDefFoundError: clojure/tools/reader/reader_types/Reader
clojure.lang.Compiler$CompilerException: Syntax error compiling at (taoensso/carmine/commands.clj:267:1).
But the class is there!
When I add the dependency on ClojureScript back into the project, the problem disappears...


weird, different classloaders issue maybe??


even if I include the exact same deps as clojurescript but not cljs itself, I get this problem


some ideas: :0, check if cljs pulls in a dep from somewhere else you're not seeing, also try to remove all generated classes when switching deps. (find . -iname "*.class") or something.


When I use carmine as the only dep it works. It must be some combination of deps... I'll try bisecting. Removing .class files is not a problem here, since I'm using boot

👍 3

But weirdly enough that doesn't have a dep on tools.reader


strange, it does have this:


[[org.clojure/clojure "1.8.0"]                 [org.clojure/clojurescript "0.0-2156"]
[org.clojure/tools.cli "0.3.1"]]


yeah, we had an exclusion on the clojurescript part


it's pretty bad when a cross-platform dep has a dependency on clojurescript

👍 3

well at least you found it 🙂.


thanks for the mental support 🙂

👍 3

I've narrowed it down but am still baffled that I'm losing 8.5s somewhere… If -verbose:gc does what I expect then I am losing about 0.1s to GC. The outer function store-tuple is recorded at ~10s and consists of a call to two functions insert-tuple-returning-id (617ms) and insert-elements (806ms) so about 1.5s of clock time between them. What am I missing?


Okay so I wasn't seeing the with-transcation and clearly this takes time. If I remove that the time drops to 19s but is easier to explain. That said, 19s to insert something like 5.5k records doesn't sound right either.


Actually rather puzzling, I spend 10s inserting the 1,000 tuple records and the same 10s inserting the 4,500 odd element records


I was going to mention it 🙂 .there's allot more going on than just your functions.

👍 3

This is the timings with transactions removed and all indices (except the foreign key between tuples and elements) also removed. The logged time for jdbc-insert-tuple and jdbc-insert-elements are for profile/p wrapping calls to jdbc/execute-one! with SQL for inserting a tuple and 5 elements respectively.


9s to insert 1,000 records (these records are not much, the tuple record is literally two id's and an integer) doesn't sound right. I'm passing the result of a call to next.jdbc/get-datasource as my data source. I am assuming that means it uses one connection and isn't reconnecting to the db on each insert. That's my next assumption to test.


Oh ho ho, this does not appear to be a safe assumption


MySQL server connection count goes up by 2,000 on each test run


I have completely misunderstood what a next.jdbc data source is


So, using with-open and a single connection insert time for 1000 tuples (about 6000 records) drops to 2.9s!

👍 3

btw. inserting records like this is sloooow in any language.


depending on your usecase you'll win by doing batch inserts


somethings I've done in the past are:


1. write to csv and use load in file <-- extremely fast


2. use psql or mysql tools to do the load file and just call it from clojure/python etc.


3. use kafka/kinesis to write fast out of my app, and have another process read big chunks of records and insert into a db.


Thanks. This will all be sitting behind an API eventually and the degenerate case of inserting a million tuples is probably unlikely. But I need inserting a few thousand to be plausibly performant. Of course this is all running on an out of the box MySQL config on my laptop, probably could be better.

👍 3

i just realized that nubank also acquired the elixir company this january. can i start hoping for an official beam clojure?


There seems to be a lot of development in 🙂


Not "official" though


nice!. I'm playing around with it now.


The Elixir assets were given to the community and Jose formed a new company around Elixir called Dashbit


i heard about the acquisition and his new company on the changelog. i was wondering what was the rationale between acquiring two prominent open source programming language companies so quickly


Is there a clean way to access the ‘original var’ inside a with-redefs? I’m wrapping a function and want to replace all calls to the original function with my wrapper fn within a given scope (but still have the wrapper fn call the original fn).


I guess I’ll just do something like

(let [f some.ns/the-original-fn]
  (defn my-wrapper-fn [& args]
    (apply f args)))

Darin Douglass13:07:57

heh, was just typing that up :thumbsup:

Darin Douglass14:07:23

well using with-redefs instead of re-`defn`ing it


what if I’m redefing a macro though?

Darin Douglass14:07:07

that won't work b/c you can't assign a macro

Darin Douglass14:07:45

user> (let [original-and and])
Syntax error compiling at (*cider-repl(clj)*:95185:17).
Can't take value of a macro: #'clojure.core/and


yeah, that was my thought


but I suppose it’s not really a problem because it seems you can’t with-redef macros either

Ben Sless16:07:30

Any recommendation / best practices for checking if an infinite loop inside a thread terminated abnormally? The two I can come up with with are polling with a timeout and sharing an error channel between the task thread and the calling thread. Any other options I'm missing? (beside whole buy-ins like suprev)? Which one would you say is preferable?


can you wrap the infinite loop in a future and use realized? to check whether it has terminated?

Ben Sless05:07:57

The infinite loop is already wrapped in a async/thread. I can check if it terminated with poll!. I was wondering if there's a better way


I think there’s an executor that can restart things automatically for you. Can also use an uncaughtexeptionhandler for info about it


newSingleThreadExecutor(ThreadFactory threadFactory) and provide a threadfactory that creates threads doing your infinite loop?

Ben Sless16:07:56

I'm actually not necessarily interested in restarting in the case of failure. I might want to just let it fail and return the exception as data


sounds like async/thread might work a treat for that then

Ben Sless16:07:56

Same problems I enumerated previously. I tried to make the question slightly generic, but in my particular use case I'm already using async/thread. The problem with an infinite loop running in it being that <!!ing from the returned channel will block indefinitely unless there's an error. So I need to poll, but polling can be too quick, and then we start bringing timeouts into the picture, or error channels

Ben Sless17:07:55

Another option with slightly less manual work will be async/merge ing them then blocking take from there, but it just reduces the problem to a single instance instead of multiple ones, doesn't address the underlying issue.


Does anyone here use an AWS Lambda for signing Maven artifacts?


(or some other mitigation to isolate the GPG key from the CI system)


I'm trying to import classes in a package[1] which has a CamelCase name. after adding the dependency to my Leiningen project and restarting the REPL (upon which the jar and pom were downloaded as expected), clojure gives me a ClassNotFoundException when I try and (import '(org.HdrHistogram Histogram)) [1]


small thing aside from your issue - ' is optional with import due to the way it's parsed, I suggest not using it

thanks2 3

user=> (import '( OutputStream))
user=> (import (java.nio ByteBuffer))


as descibed, those sound like correct things to do


lein classpath should show you your classpath - verify the dependency jar is in there

👍 3

should be at ~/.m2/repository/groupId/artifactId/artifactId-version.jar


wherever that is, jar tf <that.jar> | grep Histogram to check the class is in the jar


stepping away, but those would be my first checks


thanks! strangely enough, the jar is there and the class is in it, but the path to the jar is not in the lein classpath for this project (although, as I said, it got downloaded only after adding it to that project). I'll keep digging...


@euccastro Try lein clean and then lein classpath, just in case Leiningen has gotten stale.


@seancorfield thanks! I did that and lein classpath | grep togram still outputs nothing


@euccastro can you share your :dependencies [] from your project.clj?


you should add a dependency that doesn't exist next to your hdrhistogram dependency and see if you get an error


duh-- sorry, my bad; I had added the dependency to :plugins not :dependencies :man-facepalming:


that would do it


got befuddled by the fact that it got downloaded anyway 😳


sorry for the noise, and thanks all for the help!


I am trying to parse a given date string - "5/9/18" or "12/23/18" to a java.util.Date for inserting into datomic, what will be a good way to do that ?



user=> (java.time.LocalDate/parse "5/9/18" (java.time.format.DateTimeFormatter/ofPattern "M/d/yy"))
#object[java.time.LocalDate 0x2a28bf25 "2018-05-09"]
user=> (java.time.LocalDate/parse "12/23/18" (java.time.format.DateTimeFormatter/ofPattern "M/d/yy"))
#object[java.time.LocalDate 0x6c54bc3 "2018-12-23"]
Does Datomic support Java Time types?


or alternatively

user=> (import (java.text SimpleDateFormat))
user=> (let [format (SimpleDateFormat. "yyyy-MM-dd")] (.parse format "2009-12-31"))
#inst "2009-12-31T06:00:00.000-00:00"


Yeah but I try to encourage folks to use Java Time unless they can't 🙂


good point 🙂


Admittedly, it's a lot more code if you need to ultimately end up with a java.util.Date:

user=> (-> "5/9/18" (java.time.LocalDate/parse (java.time.format.DateTimeFormatter/ofPattern "M/d/yy")) (.atStartOfDay (java.time.ZoneId/systemDefault)) (.toInstant) (java.util.Date/from))
#inst "2018-05-09T07:00:00.000-00:00"
user=> (-> "12/23/18" (java.time.LocalDate/parse (java.time.format.DateTimeFormatter/ofPattern "M/d/yy")) (.atStartOfDay (java.time.ZoneId/systemDefault)) (.toInstant) (java.util.Date/from))
#inst "2018-12-23T08:00:00.000-00:00"


But it underscores that you do need to think about timezones at some point 🙂


@U11BV7MTK I tried that but the day is one day off -

(.parse (SimpleDateFormat. "MM/dd/yy") "5/10/18")
;; => #inst "2018-05-09T21:00:00.000-00:00"


Exactly my point! Timezones!


some dbs support a Date object without time which is probably what you want otherwise you'll always be chasing timezone stuff


I am still missing the point, how is the timezone coming in the above picture, why is the day one day off


It isn't one day off. It's three hours adjusted from UTC.


What timezone are you in @murtaza52?


East Africa Timezone - EAT


That same "simple" code for me

user=> (.parse (java.text.SimpleDateFormat. "MM/dd/yy") "5/10/18")
#inst "2018-05-10T07:00:00.000-00:00"
because I'm in Pacific time.


the trouble comes from the fact that right "now" has two different days depending on where in the world you are


So I'm -7 and you're +3.


Current time in East Africa Time ‎(UTC+3)‎ 10:53 PM


Current time in Pacific Daylight Time ‎(UTC-7)‎ 12:53 PM


Current time in Coordinated Universal Time ‎(UTC)‎ 7:54 PM


This is why Joda Time was created and then Java Time (the successor to Joda Time, which was then added to Java 8 -- and most of java.util.Date is deprecated).


(this is also why it's so important to have all your servers and all your databases and all your JVMs set to the same timezone, preferably UTC)

👍 3

Does that help @murtaza52? (time is hard because of this sort of thing)


I would understand that it returns different dates if I did (now), however I would expect that when I parse it just returns me that date in my current timzone, but whyc change the date itself ?


@seancorfield this still guves the day off -

(-> "5/9/18"
     (java.time.format.DateTimeFormatter/ofPattern "M/d/yy"))
;; => #inst "2018-05-08T21:00:00.000-00:00"


As I said, that is correct because it is adjusted to your timezone. But if you want it in UTC, use (java.time.ZoneId/of "UTC") instead of systemDefault.


And JVM/OS timezone file updates might also provide a hiccup or two. I'm a fan of UTC whenever possible


Here's my default (UTC-7):

user=> (-> "5/9/18" (java.time.LocalDate/parse (java.time.format.DateTimeFormatter/ofPattern "M/d/yy")) (.atStartOfDay (java.time.ZoneId/systemDefault)) (.toInstant) (java.util.Date/from))
#inst "2018-05-09T07:00:00.000-00:00"
user=> (-> "12/23/18" (java.time.LocalDate/parse (java.time.format.DateTimeFormatter/ofPattern "M/d/yy")) (.atStartOfDay (java.time.ZoneId/systemDefault)) (.toInstant) (java.util.Date/from))
#inst "2018-12-23T08:00:00.000-00:00"
and here it is in UTC:
user=> (-> "12/23/18" (java.time.LocalDate/parse (java.time.format.DateTimeFormatter/ofPattern "M/d/yy")) (.atStartOfDay (java.time.ZoneId/of "UTC")) (.toInstant) (java.util.Date/from))
#inst "2018-12-23T00:00:00.000-00:00"
user=> (-> "5/9/18" (java.time.LocalDate/parse (java.time.format.DateTimeFormatter/ofPattern "M/d/yy")) (.atStartOfDay (java.time.ZoneId/of "UTC")) (.toInstant) (java.util.Date/from))
#inst "2018-05-09T00:00:00.000-00:00"


Note the time portion in the default version: 07 in May, 08 in December. Due to daylight savings time changes, in addition to my timezone.


@murtaza52 And here are those two dates in your timezone:

user=> (-> "12/23/18" (java.time.LocalDate/parse (java.time.format.DateTimeFormatter/ofPattern "M/d/yy")) (.atStartOfDay (java.time.ZoneId/of "Africa/Nairobi")) (.toInstant) (java.util.Date/from))
#inst "2018-12-22T21:00:00.000-00:00"
user=> (-> "5/9/18" (java.time.LocalDate/parse (java.time.format.DateTimeFormatter/ofPattern "M/d/yy")) (.atStartOfDay (java.time.ZoneId/of "Africa/Nairobi")) (.toInstant) (java.util.Date/from))
#inst "2018-05-08T21:00:00.000-00:00"
(took me a while to figure out a zone ID that corresponded to EAT)


ok these dates are for events that happened in a timezone in US, it could be any of the US timezones, and I dont have that info available, however it happened on that particular date, and when I store it in the DB that is what I want to reflect, how should I parse them ?


You have to know the timezone to get it right. Do you know the lat/lon of the event location? You can deduce timezone from lat/lon.


(or the city/state -- either way you'll need some service to lookup the TZ at the date of the event since the offset can change due to daylight savings time -- hence my 7/8 hour offset being different in May and December)


Some parts of the US observe DST and some don't. Some states have parts in one timezone and parts in another timezone (or observe DST differently in different parts of the state!).


(-> "5/9/18"
     (java.time.format.DateTimeFormatter/ofPattern "M/d/yy"))
     (java.time.ZoneId/of "UTC"))
;; => #inst "2018-05-09T00:00:00.000-00:00"
So is UTC the solution, if I use UTC then I assume it will not ad any timezone offsets, and thus the date represented in the string be preserved ?


If you really only care about the date, you could probably get away with sticking noon as a time on the end and parse that since that will preserve the date within all of the US timezones -- but that will be a different date to where you are in EAT...


will making it a UTC timzeone have similar effect ? (check the code above)


UTC is UTC everywhere. But be careful that your database doesn't adjust the timezone when you're storing/reading dates.


(hence my admonition that server, database, and JVM should all be set to the same timezone, preferably UTC)


thanks will check that


JVM ? does it also have a timzeone setting ?


Yup, you can specify it via a JVM option at startup.


You can have your JVM and your database on the same server and have all three set to different timezones.


(but you want to ensure they are all set to the same timezone 🙂 )


This is always an issue for us when our data center on the East Coast (US) stands up a brand new server for us -- they always leave it on Eastern time, even though we always specify we want it set to UTC, and we file a ticket, and they fix it 🙂


cool appreciate the info !


I know you guys are discussing serious stuff that matters to software developers, but it reminds me of this song:

🎶 3

@seancorfield this is what I came up with -

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

(defn java-date->zoned-date-time
  (jt/zoned-date-time (jt/local-date-time jud "UTC") "UTC"))

(defn string->java-date
  (jt/java-date (jt/zoned-date-time (jt/local-date "M/d/yy" s)
                                    (jt/local-time 12 0 0)
  (string->java-date "5/8/18")
  (java-date->zoned-date-time (string->java-date "5/8/18")))


do I still need to set all my servers/ db / jvm to utc, bcoz in the above I am explicitly using UTC time when reading from a string->zoned-date-time->java-date before storing in db, and then I read it back as UTC time to zoned-date-time.


another question, does it make more sense to just using java.time.Instant and then store everything as milliseconds (bigdec) in the db, rather than java.util.Date


this is the second approach I was talking about -

(defn string->epoch-milli
     (jt/zoned-date-time (jt/local-date "M/d/yy" s)
                         (jt/local-time 12 0 0)

(defn epoch-milli->zoned-date-time
  (jt/zoned-date-time (jt/instant v)

  (string->epoch-milli "5/8/18")
  (epoch-milli->zoned-date-time (string->epoch-milli "5/8/18")))


Now I dont have to worry about time zones on servers / dbs /jvm (my assumption). Also dont have to deal with java.util.Date. I just save the bigdec in my db. Is there any disadvantage to this approach, do I loose some db functionality when I use this (Ia ssume I can still do all sort of query comparisons using the bigdec num)


There are some people who store date/time as plain milliseconds and do all their conversions in their app code. I think that's a waste of perfectly good functionality in SQL and in the database. Setting everything to UTC and working with date/time in UTC is a widely accepted approach and it's what I would recommend. I don't know what problems you'll run into with storing date/time as milliseconds but I suspect you'll end up with a lot of unnecessary boilerplate code to convert to/from actual dates -- and you'll only need to miss one conversion in one place to introduce a bug in one of your queries...


@murtaza52 A java.util.Date is in UTC. And is just a number of milliseconds past a certain point. UTC does not suffer from daylight savings problems as some TZs do. When you print the java.util.Date the JVM finds your TZ (if you haven't set the TZ on the JVM) and uses that. That leads some people to think that java.util.Date somehow contains the TZ attribute of their country, which it does not.


@U0D5RN0S1 thanks for the clarification