83ddf5c76f26ec09640f4411d092b4bd22c15608
[nit.git] / lib / core / time.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2008 Floréal Morandat <morandat@lirmm.fr>
4 # Copyright 2014 Alexandre Terrasa <alexandre@moz-code.org>
5 #
6 # This file is free software, which comes along with NIT. This software is
7 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
8 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
9 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
10 # is kept unaltered, and a notification of the changes is added.
11 # You are allowed to redistribute it and sell it, alone or is a part of
12 # another product.
13
14 # Management of time and dates
15 module time
16
17 import text
18 import stream
19
20 in "C Header" `{
21 #include <time.h>
22 #include <sys/time.h>
23 `}
24
25 # The number of seconds elapsed since January 1, 1970
26 #
27 # Uses the Unix function `time`.
28 fun get_time: Int `{ return time(NULL); `}
29
30 # The number of milliseconds elapsed since January 1, 1970
31 #
32 # Returns `get_microtime / 1000`
33 fun get_millitime: Int do return get_microtime / 1000
34
35 # The number of microseconds elapsed since January 1, 1970
36 #
37 # Uses the Unix function `gettimeofday`.
38 fun get_microtime: Int `{
39 struct timeval val;
40 gettimeofday(&val, NULL);
41 return val.tv_sec * 1000000 + val.tv_usec;
42 `}
43
44 redef class Sys
45 # Wait a specific number of second and nanoseconds
46 #
47 # Returns `true` if interrupted by a signal.
48 fun nanosleep(sec, nanosec: Int): Bool `{
49 const struct timespec req = {sec, nanosec};
50 return nanosleep(&req, NULL);
51 `}
52 end
53
54 redef class Float
55 # Sleep approximately `self` seconds
56 #
57 # Is not interrupted by signals.
58 fun sleep `{
59 time_t s = self;
60 long ns = (self-s) * 1000000000.0;
61 struct timespec req = {s, ns};
62
63 while (nanosleep(&req, &req)) { }
64 `}
65 end
66
67 # Time since epoch
68 extern class TimeT `{time_t`}
69
70 # Returns Time since epoch from now.
71 new `{ return time(NULL); `}
72
73 # Returns Time since epoch from `i` (expressed in seconds).
74 new from_i(i: Int) `{ return i; `}
75
76 # Update current time.
77 fun update `{ time(&self); `}
78
79 # Convert `self` to a human readable String.
80 fun ctime: String import CString.to_s `{
81 return CString_to_s( ctime(&self) );
82 `}
83
84 # Difference in secondes from start (self if the end time)
85 fun difftime(start: TimeT): Float `{ return difftime(self, start); `}
86
87 redef fun to_s do return ctime.replace("\n", "")
88
89 # Convert self to Int (expressed as seconds since epoch).
90 fun to_i: Int `{ return (int)self; `}
91 end
92
93 # Time structure
94 extern class Tm `{struct tm *`}
95
96 # Create a new Time structure expressed in Coordinated Universal Time (UTC).
97 new gmtime `{
98 struct tm *tm;
99 time_t t = time(NULL);
100 tm = gmtime(&t);
101 return tm;
102 `}
103
104 # Create a new Time structure expressed in UTC from `t`.
105 new gmtime_from_timet(t: TimeT) `{
106 struct tm *tm;
107 tm = gmtime(&t);
108 return tm;
109 `}
110
111 # Create a new Time structure expressed in the local timezone.
112 new localtime `{
113 struct tm *tm;
114 time_t t = time(NULL);
115 tm = localtime(&t);
116 return tm;
117 `}
118
119 # Create a new Time structure expressed in the local timezone from `t`.
120 new localtime_from_timet(t: TimeT) `{
121 struct tm *tm;
122 tm = localtime(&t);
123 return tm;
124 `}
125
126 # Convert `self` as a TimeT.
127 fun to_timet: TimeT `{ return mktime(self); `}
128
129 # Seconds after the minute.
130 fun sec: Int `{ return self->tm_sec; `}
131
132 # Minutes after the hour.
133 fun min: Int `{ return self->tm_min; `}
134
135 # hours since midnight.
136 fun hour: Int `{ return self->tm_hour; `}
137
138 # Day of the month.
139 fun mday: Int `{ return self->tm_mday; `}
140
141 # Months since January.
142 fun mon: Int `{ return self->tm_mon; `}
143
144 # Years since 1900.
145 fun year: Int `{ return self->tm_year; `}
146
147 # Days since Sunday.
148 fun wday: Int `{ return self->tm_wday; `}
149
150 # Days since January 1st.
151 fun yday: Int `{ return self->tm_yday; `}
152
153 # Is `self` in Daylight Saving Time.
154 fun is_dst: Bool `{ return self->tm_isdst; `}
155
156 # Convert `self` to a human readable String.
157 private fun asctime: CString `{ return asctime(self); `}
158
159 # Convert `self` to a human readable String corresponding to `format`.
160 # TODO document allowed format.
161 fun strftime(format: String): String import String.to_cstring, CString.to_s `{
162 char* buf, *c_format;
163
164 buf = (char*)malloc(100);
165 c_format = String_to_cstring(format);
166
167 strftime(buf, 100, c_format, self);
168 String s = CString_to_s(buf);
169 free(buf);
170 return s;
171 `}
172
173 redef fun to_s do return asctime.to_s.replace("\n", "")
174 end
175
176 # Date using the international format defined by ISO 8601.
177 #
178 # Usage:
179 #
180 # # By default ISODate at today.
181 # var date = new ISODate
182 # var tm = new Tm.localtime
183 # assert date.year == tm.year + 1900
184 # assert date.month == tm.mon + 1
185 # assert date.day == tm.mday
186 #
187 # # ISODate can be initialized from a String.
188 # date = new ISODate.from_string("1970-01-01T00:00:00Z")
189 # assert date.year == 1970
190 # assert date.month == 1
191 # assert date.day == 1
192 #
193 # # ISODate can be printed as String following the ISO format.
194 # assert date.to_s == "1970-01-01T00:00:00Z"
195 #
196 # Note that only the `YYYY-MM-DDTHH:MM:SSZ` is supported for now.
197 #
198 # See <http://www.w3.org/QA/Tips/iso-date>
199 class ISODate
200 super Comparable
201
202 # UTC years as Int.
203 var year: Int is noinit
204
205 # UTC months as Int (`1` for January).
206 var month: Int is noinit
207
208 # UTC days as Int (starting at `1`).
209 var day: Int is noinit
210
211 # UTC hours as Int.
212 var hours: Int is noinit
213
214 # UTC minutes as Int.
215 var minutes: Int is noinit
216
217 # UTC seconds as Int.
218 var seconds: Int is noinit
219
220 # UTC timezone marker.
221 #
222 # Note that I don't know what will happen if you change this value...
223 var timezone = "Z"
224
225 init do
226 var t = new Tm.localtime
227 year = 1900 + t.year
228 month = t.mon + 1
229 day = t.mday
230 hours = t.hour
231 minutes = t.min
232 seconds = t.sec
233 end
234
235 # Init `self` from a ISODate formatted string.
236 init from_string(str: String) do
237 year = str.substring(0, 4).to_i
238 month = str.substring(5, 2).to_i
239 day = str.substring(8, 2).to_i
240 hours = str.substring(11, 2).to_i
241 minutes = str.substring(14, 2).to_i
242 seconds = str.substring(17, 2).to_i
243 timezone = str.substring(19, str.length)
244 end
245
246 redef fun to_s do
247 var buff = new FlatBuffer
248 buff.append year.to_s
249 buff.add '-'
250 if month < 10 then buff.add '0'
251 buff.append month.to_s
252 buff.add '-'
253 if day < 10 then buff.add '0'
254 buff.append day.to_s
255 buff.add 'T'
256 if hours < 10 then buff.add '0'
257 buff.append hours.to_s
258 buff.add ':'
259 if minutes < 10 then buff.add '0'
260 buff.append minutes.to_s
261 buff.add ':'
262 if seconds < 10 then buff.add '0'
263 buff.append seconds.to_s
264 buff.append timezone
265 return buff.write_to_string
266 end
267
268 redef type OTHER: ISODate
269
270 # TODO handle timezones
271 redef fun <(o) do return to_s < o.to_s
272 end