Skip to content

Instantly share code, notes, and snippets.

@lightningspirit
Created May 8, 2024 21:26
Show Gist options
  • Save lightningspirit/85a6804963e44fff46ffc542cec8cda5 to your computer and use it in GitHub Desktop.
Save lightningspirit/85a6804963e44fff46ffc542cec8cda5 to your computer and use it in GitHub Desktop.
[WIP] OCaml Date implementation
open Unix
type date = {
year : int;
month : int;
day : int;
}
exception InvalidDate of string
let is_leap_year year =
year mod 4 = 0 && (year mod 100 <> 0 || year mod 400 = 0)
let days_in_year year =
if is_leap_year year then 366 else 365
let days_in_month year month =
match month with
| 1 | 3 | 5 | 7 | 8 | 10 | 12 -> 31
| 4 | 6 | 9 | 11 -> 30
| 2 -> if is_leap_year year then 29 else 28
| _ -> 0
let is_valid_date { year; month; day } =
month >= 1 && month <= 12 && day >= 1 && (days_in_month year day) > 0
let create year month day =
let date = { year; month; day } in
match is_valid_date date with
| true -> date
| _ -> raise (InvalidDate "Invalid date")
let today () =
let tm = Unix.localtime (Unix.time ()) in
create (tm.tm_year + 1900) (tm.tm_mon + 1) tm.tm_mday
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment