Skip to content

Commit e858577

Browse files
pm5cuihtlauac
andauthored
Cookbook: Display Formatted Date and Time (#3158)
* Cookbook: Display Formatted Date and Time * Update data/cookbook/display-formatted-date-time/00-stdlib.ml --------- Co-authored-by: Cuihtlauac Alvarado <cuihtlauac@users.noreply.github.com>
1 parent 29d1076 commit e858577

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
---
2+
packages: []
3+
discussion: |
4+
- **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.
5+
- **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.
6+
---
7+
8+
(* The `unix` library, which ships with OCaml's standard library, provides
9+
functions to work with dates and times. *)
10+
let today: Unix.tm = Unix.localtime (Unix.time ());;
11+
12+
(* The `Unix.tm` type represents date and time, but it lacks a pretty printer.
13+
We can define one for it. *)
14+
let pp_tm ppf t =
15+
Format.fprintf ppf "%4d-%02d-%02dT%02d:%02d:%02dZ" (t.Unix.tm_year + 1900)
16+
(t.Unix.tm_mon + 1) t.Unix.tm_mday t.Unix.tm_hour t.Unix.tm_min
17+
t.Unix.tm_sec;;
18+
19+
(* Then define a function that converts `Unix.tm` to string. *)
20+
let show_tm = Format.asprintf "%a" pp_tm;;
21+
22+
Format.printf "The current date and time is %a" pp_tm today;;
23+
24+
print_endline ("The current date and time is " ^ show_tm today);;

0 commit comments

Comments
 (0)