Skip to content

Instantly share code, notes, and snippets.

@jasalt
Last active December 15, 2024 07:12
Show Gist options
  • Save jasalt/50b27315e61d35cee9b9325510921a42 to your computer and use it in GitHub Desktop.
Save jasalt/50b27315e61d35cee9b9325510921a42 to your computer and use it in GitHub Desktop.
utils.phel
(ns my-ns\utils)
# WIP general utils for Phel programs
# Dates
# TODO See Carbon DateTime library if more complex stuff is required
# https://carbon.nesbot.com/
(def date-str-format "Y-m-d")
(defn valid-date-str? [date-str] # TODO to utils
"Uses the sloppy PHP DateTime constructor, validating it's returned string
presentation afterwards to finish the validation.
Otherwise E.g. 2024-99-99 would pass otherwise."
(let [fmt date-str-format
dt (php/:: \DateTimeImmutable (createFromFormat fmt date-str))]
(when (= "DateTimeImmutable" (php/get_class dt))
(= date-str (php/-> dt (format fmt))))))
(defn first-day-of-month
"Get first date of month for given `date-str` YYYY-MM-DD returning string"
[date-str]
(when-not (valid-date-str? date-str)
(throw (php/new \Exception "Date format is invalid for fn first-day-of-month")))
(let [fmt date-str-format]
(-> (php/new \DateTimeImmutable date-str)
(php/-> (modify "first day of this month"))
(php/-> (format fmt)))))
(defn last-day-of-month
"Get first date of month for given `date-str` YYYY-MM-DD returning string"
[date-str]
(when-not (valid-date-str? date-str)
(throw (php/new \Exception "Date format is invalid for fn last-day-of-month")))
(let [fmt date-str-format]
(-> (php/new \DateTimeImmutable date-str)
(php/-> (modify "last day of this month"))
(php/-> (format fmt)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment