Skip to content

Instantly share code, notes, and snippets.

@humorless
Created August 17, 2024 07:27
Show Gist options
  • Save humorless/c5ca6a8ae409962d6f3e020fef24a156 to your computer and use it in GitHub Desktop.
Save humorless/c5ca6a8ae409962d6f3e020fef24a156 to your computer and use it in GitHub Desktop.
java time library

Duration

(time/duration dur-str)

ZoneId type

(def event-time-zone (java.time.ZoneId/of "Europe/Brussels"))

decided time type

  • ZonedDateTime
    • case: 生成
(java.time.ZonedDateTime/ofInstant
     (.toInstant ^java.util.Date value)
     event-time-zone)
  • ZonedDateTime
    • case: 取得 hour, minute, time。
    • 取得 day-of-week, day-of-month, month
(let [zone-id (ZoneId/systemDefault)
        zdt (ZonedDateTime/ofInstant instant zone-id)
        day-of-week (.getValue (.getDayOfWeek zdt))
        month (.getMonthValue zdt)
        day-of-month (.getDayOfMonth zdt)
        time (.toLocalTime zdt)]
    {:hour (.getHour time)
     :minute (.getMinute time)
     :day-of-week day-of-week
     :month month
     :day-of-month day-of-month})
  • ZonedDateTime
    • case: 取得 minute
(time/truncate-to (time/local-time time) :minutes)
  • ZonedDateTime
    • case: 取得 Month and Day
(time/format "dd.MM" time)
  • ZonedDateTime
    • case: 取得 week day
(time/day-of-week time)

undecided time type

  • LocalDate
  • LocalTime
  • LocalDateTime

Clojure example

  • from String
;; start-date is "2024-08-17"
;; start-time is "09:00"

;; local-date 可以用 String 來初始化
;; local-time 可以用 String 來初始化
;; local-date-time 可以用其它的 time entity 來初始化
### ;; zoned-date-time 可以用 local-date-time 搭配 time zone 來初始化

(let [local-date (time/local-date start-date)
      local-time (time/local-time start-time)
      local-date-time (time/local-date-time local-date local-time)
      start    (time/zoned-date-time local-date-time db/event-time-zone)]
...
)
  • From ZonedDateTime
(time/local-date (:session/time session))

Java counterpart

建立日期時間的方式,可以用parse的方式。

val date = LocalDate.parse("2021-01-01")
val time = LocalTime.parse("13:40:50")
val dateTime = LocalDateTime.parse("2021-01-01T13:40:50")

如果要用自定的格式來建立日期時間,就可以使用DateTimeFormatter

val dateTime = LocalDateTime.parse(
  "2021/01/01 13:40:50",
  DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment