@@ -60,17 +60,52 @@ defmodule Time do
60
60
@ doc """
61
61
Returns the current time in UTC.
62
62
63
+ You can pass a time unit to automatically truncate the resulting time.
64
+
65
+ The default unit if none gets passed is `:native` which results on a default resolution of microseconds.
66
+
63
67
## Examples
64
68
65
69
iex> time = Time.utc_now()
66
70
iex> time.hour >= 0
67
71
true
68
72
73
+ iex> time = Time.utc_now(:second)
74
+ iex> time.microsecond
75
+ {0, 0}
76
+
69
77
"""
70
78
@ doc since: "1.4.0"
71
- @ spec utc_now ( Calendar . calendar ( ) ) :: t
72
- def utc_now ( calendar \\ Calendar.ISO ) do
73
- { :ok , _ , time , microsecond } = Calendar.ISO . from_unix ( :os . system_time ( ) , :native )
79
+ @ spec utc_now ( Calendar . calendar ( ) | :native | :microsecond | :millisecond | :second ) :: t
80
+ def utc_now ( calendar_or_time_unit \\ Calendar.ISO ) do
81
+ case calendar_or_time_unit do
82
+ unit when unit in [ :native , :microsecond , :millisecond , :second ] ->
83
+ utc_now ( unit , Calendar.ISO )
84
+
85
+ calendar ->
86
+ utc_now ( :native , calendar )
87
+ end
88
+ end
89
+
90
+ @ doc """
91
+ Returns the current time in UTC, supporting a precision and a specific calendar.
92
+
93
+ ## Examples
94
+
95
+ iex> time = Time.utc_now(:microsecond, Calendar.ISO)
96
+ iex> time.hour >= 0
97
+ true
98
+
99
+ iex> time = Time.utc_now(:second, Calendar.ISO)
100
+ iex> time.microsecond
101
+ {0, 0}
102
+
103
+ """
104
+ @ doc since: "1.19.0"
105
+ @ spec utc_now ( :native | :microsecond | :millisecond | :second , Calendar . calendar ( ) ) :: t
106
+ def utc_now ( time_unit , calendar )
107
+ when time_unit in [ :native , :microsecond , :millisecond , :second ] do
108
+ { :ok , _ , time , microsecond } = Calendar.ISO . from_unix ( System . os_time ( time_unit ) , time_unit )
74
109
{ hour , minute , second } = time
75
110
76
111
iso_time = % Time {
0 commit comments