From a55449a416fecf0c8ebfc95c9ef8aa6cbd8def72 Mon Sep 17 00:00:00 2001 From: Pomin Wu Date: Wed, 11 Jun 2025 07:43:55 +0800 Subject: [PATCH 1/2] Cookbook: Display Formatted Date and Time --- .../display-formatted-date-time/00-stdlib.ml | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 data/cookbook/display-formatted-date-time/00-stdlib.ml diff --git a/data/cookbook/display-formatted-date-time/00-stdlib.ml b/data/cookbook/display-formatted-date-time/00-stdlib.ml new file mode 100644 index 0000000000..4f15f0bfa5 --- /dev/null +++ b/data/cookbook/display-formatted-date-time/00-stdlib.ml @@ -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);; From 5acbe9316daabac1271e02eb198b28b0811bd4d0 Mon Sep 17 00:00:00 2001 From: Cuihtlauac Alvarado Date: Fri, 20 Jun 2025 15:55:02 +0200 Subject: [PATCH 2/2] Update data/cookbook/display-formatted-date-time/00-stdlib.ml --- data/cookbook/display-formatted-date-time/00-stdlib.ml | 1 + 1 file changed, 1 insertion(+) diff --git a/data/cookbook/display-formatted-date-time/00-stdlib.ml b/data/cookbook/display-formatted-date-time/00-stdlib.ml index 4f15f0bfa5..b7f7a1e637 100644 --- a/data/cookbook/display-formatted-date-time/00-stdlib.ml +++ b/data/cookbook/display-formatted-date-time/00-stdlib.ml @@ -1,5 +1,6 @@ --- packages: [] +discussion: | - **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. ---