Skip to content

Cookbook: Display Formatted Date and Time #3158

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions data/cookbook/display-formatted-date-time/00-stdlib.ml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
packages: []
- **Understanding `Unix.tm`:** The `Unix.tm` structure represents a local time. This structure includes fields like `tm_year`, `tm_mon`, and `tm_mday` for year, month, and day, respectively.
- **Understanding `Format`:** Because `Unix.tm` is an abstract type, we must define a pretty printer for it. The are usually two kinds of pretty printer for a type: `pp` uses `Format.formatter` to print a value, and `show` simply converts the value to a string.
---

(* The `unix` library, which ships with OCaml's standard library, provides
functions to work with dates and times. *)
let today: Unix.tm = Unix.localtime (Unix.time ());;

(* The `Unix.tm` type represents date and time, but it lacks a pretty printer.
We can define one for it. *)
let pp_tm ppf t =
Format.fprintf ppf "%4d-%02d-%02dT%02d:%02d:%02dZ" (t.Unix.tm_year + 1900)
(t.Unix.tm_mon + 1) t.Unix.tm_mday t.Unix.tm_hour t.Unix.tm_min
t.Unix.tm_sec;;

(* Then define a function that converts `Unix.tm` to string. *)
let show_tm = Format.asprintf "%a" pp_tm;;

Format.printf "The current date and time is %a" pp_tm today;;

print_endline ("The current date and time is " ^ show_tm today);;