andrewmcveigh / cljs-time

A clj-time inspired date library for clojurescript.
342 stars 57 forks source link

Any plans to allow setters in date-times? #72

Closed livtanong closed 7 years ago

livtanong commented 8 years ago

For example, given a certain date-time, I'd like to set the month.

(def dt (date-time 2016 9 13))
...
(def new-dt (set-month dt 4))

This is useful for charting and other edge cases, as it's cumbersome to have to create a new date-time, accessing the untouched fields of the base date-time, when all you want to change is one field.

(def dt (date-time 2016 9 13))
...
(def new-dt 
  (date-time
      (year dt)
      4
      (day dt)))
danielcompton commented 8 years ago

Two options are to use plus with a period n months to do this, or write a function to encapsulate what you are doing to create new-dt.

I would argue against mutating dates, as that is historically a massive source of pain (Joda-Time and Java 8's Time libraries are both immutable, in reaction to the pain of Java Date's being mutable), and doesn't fit well with Clojure's preference for immutable data structures. AFAICT It also isn't present in clj-time, which this libraries API is based on.

andrewmcveigh commented 8 years ago

Agree with @danielcompton, there are no plans to introduce mutability into cljs-time. If you really want that, you can mutate the underlying goog.date.Date* objects, though you might get unexpected results.

livtanong commented 8 years ago

Ah, sorry, I did not communicate properly. I'm not asking for mutability at all—set-month would create a new date-time.

Edit: Pressed enter too early. I was originally hoping that a date-time was a record so I could easily just assoc a new value into one of the fields.

@danielcompton's period option isn't very good for my use, as I have to transform a bunch of past dates and convert them to "today" in order to compare their times on a chart. I felt quite silly writing the code below.

(t/local-date-time
  (t/year today)
  (t/month today)
  (t/day today)
  (t/hour datapoint)
  (t/minute datapoint))

Definitely, I can make a function to encapsulate that function, I think this operation could be useful for a few people too.

andrewmcveigh commented 7 years ago

Oh, just seeing the rest of your response right now...

I guess that I see your point somewhat, though I don't want to stray from the clj-time API. This library is purposefully a (as good as possible in js) mirror of the clj-time API, which in turn is based on the Joda-Time API.