]> git.lizzy.rs Git - rust.git/blob - src/libextra/time.rs
auto merge of #11598 : alexcrichton/rust/io-export, r=brson
[rust.git] / src / libextra / time.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #[allow(missing_doc)];
12
13 use std::io::BufReader;
14 use std::libc;
15 use std::num;
16 use std::str;
17
18 static NSEC_PER_SEC: i32 = 1_000_000_000_i32;
19
20 mod rustrt {
21     use super::Tm;
22
23     extern {
24         pub fn rust_tzset();
25         pub fn rust_gmtime(sec: i64, nsec: i32, result: &mut Tm);
26         pub fn rust_localtime(sec: i64, nsec: i32, result: &mut Tm);
27         pub fn rust_timegm(tm: &Tm) -> i64;
28         pub fn rust_mktime(tm: &Tm) -> i64;
29     }
30 }
31
32 #[cfg(unix, not(target_os = "macos"))]
33 mod imp {
34     use std::libc::{c_int, timespec};
35
36     // Apparently android provides this in some other library?
37     #[cfg(not(target_os = "android"))]
38     #[link(name = "rt")]
39     extern {}
40
41     extern {
42         pub fn clock_gettime(clk_id: c_int, tp: *mut timespec) -> c_int;
43     }
44
45 }
46 #[cfg(target_os = "macos")]
47 mod imp {
48     use std::libc::{timeval, timezone, c_int, mach_timebase_info};
49
50     extern {
51         pub fn gettimeofday(tp: *mut timeval, tzp: *mut timezone) -> c_int;
52         pub fn mach_absolute_time() -> u64;
53         pub fn mach_timebase_info(info: *mut mach_timebase_info) -> c_int;
54     }
55 }
56
57 /// A record specifying a time value in seconds and nanoseconds.
58
59
60 #[deriving(Clone, DeepClone, Eq, Encodable, Decodable)]
61 pub struct Timespec { sec: i64, nsec: i32 }
62 /*
63  * Timespec assumes that pre-epoch Timespecs have negative sec and positive
64  * nsec fields. Darwin's and Linux's struct timespec functions handle pre-
65  * epoch timestamps using a "two steps back, one step forward" representation,
66  * though the man pages do not actually document this. For example, the time
67  * -1.2 seconds before the epoch is represented by `Timespec { sec: -2_i64,
68  * nsec: 800_000_000_i32 }`.
69  */
70 impl Timespec {
71     pub fn new(sec: i64, nsec: i32) -> Timespec {
72         assert!(nsec >= 0 && nsec < NSEC_PER_SEC);
73         Timespec { sec: sec, nsec: nsec }
74     }
75 }
76
77 impl Ord for Timespec {
78     fn lt(&self, other: &Timespec) -> bool {
79         self.sec < other.sec ||
80             (self.sec == other.sec && self.nsec < other.nsec)
81     }
82 }
83
84 /**
85  * Returns the current time as a `timespec` containing the seconds and
86  * nanoseconds since 1970-01-01T00:00:00Z.
87  */
88 pub fn get_time() -> Timespec {
89     unsafe {
90         let (sec, nsec) = os_get_time();
91         return Timespec::new(sec, nsec);
92     }
93
94     #[cfg(windows)]
95     unsafe fn os_get_time() -> (i64, i32) {
96         static NANOSECONDS_FROM_1601_TO_1970: u64 = 11644473600000000;
97
98         let mut time = libc::FILETIME {
99             dwLowDateTime: 0,
100             dwHighDateTime: 0,
101         };
102         libc::GetSystemTimeAsFileTime(&mut time);
103
104         // A FILETIME contains a 64-bit value representing the number of
105         // hectonanosecond (100-nanosecond) intervals since 1601-01-01T00:00:00Z.
106         // http://support.microsoft.com/kb/167296/en-us
107         let ns_since_1601 = ((time.dwHighDateTime as u64 << 32) |
108                              (time.dwLowDateTime  as u64 <<  0)) / 10;
109         let ns_since_1970 = ns_since_1601 - NANOSECONDS_FROM_1601_TO_1970;
110
111         ((ns_since_1970 / 1000000) as i64,
112          ((ns_since_1970 % 1000000) * 1000) as i32)
113     }
114
115     #[cfg(target_os = "macos")]
116     unsafe fn os_get_time() -> (i64, i32) {
117         use std::ptr;
118         let mut tv = libc::timeval { tv_sec: 0, tv_usec: 0 };
119         imp::gettimeofday(&mut tv, ptr::mut_null());
120         (tv.tv_sec as i64, tv.tv_usec * 1000)
121     }
122
123     #[cfg(not(target_os = "macos"), not(windows))]
124     unsafe fn os_get_time() -> (i64, i32) {
125         let mut tv = libc::timespec { tv_sec: 0, tv_nsec: 0 };
126         imp::clock_gettime(libc::CLOCK_REALTIME, &mut tv);
127         (tv.tv_sec as i64, tv.tv_nsec as i32)
128     }
129 }
130
131
132 /**
133  * Returns the current value of a high-resolution performance counter
134  * in nanoseconds since an unspecified epoch.
135  */
136 pub fn precise_time_ns() -> u64 {
137     return os_precise_time_ns();
138
139     #[cfg(windows)]
140     fn os_precise_time_ns() -> u64 {
141         let mut ticks_per_s = 0;
142         assert_eq!(unsafe {
143             libc::QueryPerformanceFrequency(&mut ticks_per_s)
144         }, 1);
145         let ticks_per_s = if ticks_per_s == 0 {1} else {ticks_per_s};
146         let mut ticks = 0;
147         assert_eq!(unsafe {
148             libc::QueryPerformanceCounter(&mut ticks)
149         }, 1);
150
151         return (ticks as u64 * 1000000000) / (ticks_per_s as u64);
152     }
153
154     #[cfg(target_os = "macos")]
155     fn os_precise_time_ns() -> u64 {
156         let time = unsafe { imp::mach_absolute_time() };
157         let mut info = libc::mach_timebase_info { numer: 0, denom: 0 };
158         unsafe { imp::mach_timebase_info(&mut info); }
159         return time * ((info.numer / info.denom) as u64);
160     }
161
162     #[cfg(not(windows), not(target_os = "macos"))]
163     fn os_precise_time_ns() -> u64 {
164         let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
165         unsafe {
166             imp::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts);
167         }
168         return (ts.tv_sec as u64) * 1000000000 + (ts.tv_nsec as u64)
169     }
170 }
171
172
173 /**
174  * Returns the current value of a high-resolution performance counter
175  * in seconds since an unspecified epoch.
176  */
177 pub fn precise_time_s() -> f64 {
178     return (precise_time_ns() as f64) / 1000000000.;
179 }
180
181 pub fn tzset() {
182     unsafe {
183         rustrt::rust_tzset();
184     }
185 }
186
187 #[deriving(Clone, DeepClone, Eq, Encodable, Decodable)]
188 pub struct Tm {
189     tm_sec: i32, // seconds after the minute ~[0-60]
190     tm_min: i32, // minutes after the hour ~[0-59]
191     tm_hour: i32, // hours after midnight ~[0-23]
192     tm_mday: i32, // days of the month ~[1-31]
193     tm_mon: i32, // months since January ~[0-11]
194     tm_year: i32, // years since 1900
195     tm_wday: i32, // days since Sunday ~[0-6]
196     tm_yday: i32, // days since January 1 ~[0-365]
197     tm_isdst: i32, // Daylight Savings Time flag
198     tm_gmtoff: i32, // offset from UTC in seconds
199     tm_zone: ~str, // timezone abbreviation
200     tm_nsec: i32, // nanoseconds
201 }
202
203 pub fn empty_tm() -> Tm {
204     // 64 is the max size of the timezone buffer allocated on windows
205     // in rust_localtime. In glibc the max timezone size is supposedly 3.
206     let zone = str::with_capacity(64);
207     Tm {
208         tm_sec: 0_i32,
209         tm_min: 0_i32,
210         tm_hour: 0_i32,
211         tm_mday: 0_i32,
212         tm_mon: 0_i32,
213         tm_year: 0_i32,
214         tm_wday: 0_i32,
215         tm_yday: 0_i32,
216         tm_isdst: 0_i32,
217         tm_gmtoff: 0_i32,
218         tm_zone: zone,
219         tm_nsec: 0_i32,
220     }
221 }
222
223 /// Returns the specified time in UTC
224 pub fn at_utc(clock: Timespec) -> Tm {
225     unsafe {
226         let Timespec { sec, nsec } = clock;
227         let mut tm = empty_tm();
228         rustrt::rust_gmtime(sec, nsec, &mut tm);
229         tm
230     }
231 }
232
233 /// Returns the current time in UTC
234 pub fn now_utc() -> Tm {
235     at_utc(get_time())
236 }
237
238 /// Returns the specified time in the local timezone
239 pub fn at(clock: Timespec) -> Tm {
240     unsafe {
241         let Timespec { sec, nsec } = clock;
242         let mut tm = empty_tm();
243         rustrt::rust_localtime(sec, nsec, &mut tm);
244         tm
245     }
246 }
247
248 /// Returns the current time in the local timezone
249 pub fn now() -> Tm {
250     at(get_time())
251 }
252
253
254 impl Tm {
255     /// Convert time to the seconds from January 1, 1970
256     pub fn to_timespec(&self) -> Timespec {
257         unsafe {
258             let sec = match self.tm_gmtoff {
259                 0_i32 => rustrt::rust_timegm(self),
260                 _     => rustrt::rust_mktime(self)
261             };
262
263             Timespec::new(sec, self.tm_nsec)
264         }
265     }
266
267     /// Convert time to the local timezone
268     pub fn to_local(&self) -> Tm {
269         at(self.to_timespec())
270     }
271
272     /// Convert time to the UTC
273     pub fn to_utc(&self) -> Tm {
274         at_utc(self.to_timespec())
275     }
276
277     /**
278      * Return a string of the current time in the form
279      * "Thu Jan  1 00:00:00 1970".
280      */
281     pub fn ctime(&self) -> ~str { self.strftime("%c") }
282
283     /// Formats the time according to the format string.
284     pub fn strftime(&self, format: &str) -> ~str {
285         strftime(format, self)
286     }
287
288     /**
289      * Returns a time string formatted according to RFC 822.
290      *
291      * local: "Thu, 22 Mar 2012 07:53:18 PST"
292      * utc:   "Thu, 22 Mar 2012 14:53:18 UTC"
293      */
294     pub fn rfc822(&self) -> ~str {
295         if self.tm_gmtoff == 0_i32 {
296             self.strftime("%a, %d %b %Y %T GMT")
297         } else {
298             self.strftime("%a, %d %b %Y %T %Z")
299         }
300     }
301
302     /**
303      * Returns a time string formatted according to RFC 822 with Zulu time.
304      *
305      * local: "Thu, 22 Mar 2012 07:53:18 -0700"
306      * utc:   "Thu, 22 Mar 2012 14:53:18 -0000"
307      */
308     pub fn rfc822z(&self) -> ~str {
309         self.strftime("%a, %d %b %Y %T %z")
310     }
311
312     /**
313      * Returns a time string formatted according to ISO 8601.
314      *
315      * local: "2012-02-22T07:53:18-07:00"
316      * utc:   "2012-02-22T14:53:18Z"
317      */
318     pub fn rfc3339(&self) -> ~str {
319         if self.tm_gmtoff == 0_i32 {
320             self.strftime("%Y-%m-%dT%H:%M:%SZ")
321         } else {
322             let s = self.strftime("%Y-%m-%dT%H:%M:%S");
323             let sign = if self.tm_gmtoff > 0_i32 { '+' } else { '-' };
324             let mut m = num::abs(self.tm_gmtoff) / 60_i32;
325             let h = m / 60_i32;
326             m -= h * 60_i32;
327             s + format!("{}{:02d}:{:02d}", sign, h as int, m as int)
328         }
329     }
330 }
331
332 /// Parses the time from the string according to the format string.
333 pub fn strptime(s: &str, format: &str) -> Result<Tm, ~str> {
334     fn match_str(s: &str, pos: uint, needle: &str) -> bool {
335         let mut i = pos;
336         for ch in needle.bytes() {
337             if s[i] != ch {
338                 return false;
339             }
340             i += 1u;
341         }
342         return true;
343     }
344
345     fn match_strs(ss: &str, pos: uint, strs: &[(~str, i32)])
346       -> Option<(i32, uint)> {
347         let mut i = 0u;
348         let len = strs.len();
349         while i < len {
350             match strs[i] { // can't use let due to let-pattern bugs
351                 (ref needle, value) => {
352                     if match_str(ss, pos, *needle) {
353                         return Some((value, pos + needle.len()));
354                     }
355                 }
356             }
357             i += 1u;
358         }
359
360         None
361     }
362
363     fn match_digits(ss: &str, pos: uint, digits: uint, ws: bool)
364       -> Option<(i32, uint)> {
365         let mut pos = pos;
366         let len = ss.len();
367         let mut value = 0_i32;
368
369         let mut i = 0u;
370         while i < digits {
371             if pos >= len {
372                 return None;
373             }
374             let range = ss.char_range_at(pos);
375             pos = range.next;
376
377             match range.ch {
378               '0' .. '9' => {
379                 value = value * 10_i32 + (range.ch as i32 - '0' as i32);
380               }
381               ' ' if ws => (),
382               _ => return None
383             }
384             i += 1u;
385         }
386
387         Some((value, pos))
388     }
389
390     fn match_fractional_seconds(ss: &str, pos: uint) -> (i32, uint) {
391         let len = ss.len();
392         let mut value = 0_i32;
393         let mut multiplier = NSEC_PER_SEC / 10;
394         let mut pos = pos;
395
396         loop {
397             if pos >= len {
398                 break;
399             }
400             let range = ss.char_range_at(pos);
401
402             match range.ch {
403                 '0' .. '9' => {
404                     pos = range.next;
405                     // This will drop digits after the nanoseconds place
406                     let digit = range.ch as i32 - '0' as i32;
407                     value += digit * multiplier;
408                     multiplier /= 10;
409                 }
410                 _ => break
411             }
412         }
413
414         (value, pos)
415     }
416
417     fn match_digits_in_range(ss: &str, pos: uint, digits: uint, ws: bool,
418                              min: i32, max: i32) -> Option<(i32, uint)> {
419         match match_digits(ss, pos, digits, ws) {
420           Some((val, pos)) if val >= min && val <= max => {
421             Some((val, pos))
422           }
423           _ => None
424         }
425     }
426
427     fn parse_char(s: &str, pos: uint, c: char) -> Result<uint, ~str> {
428         let range = s.char_range_at(pos);
429
430         if c == range.ch {
431             Ok(range.next)
432         } else {
433             Err(format!("Expected {}, found {}",
434                 str::from_char(c),
435                 str::from_char(range.ch)))
436         }
437     }
438
439     fn parse_type(s: &str, pos: uint, ch: char, tm: &mut Tm)
440       -> Result<uint, ~str> {
441         match ch {
442           'A' => match match_strs(s, pos, [
443               (~"Sunday", 0_i32),
444               (~"Monday", 1_i32),
445               (~"Tuesday", 2_i32),
446               (~"Wednesday", 3_i32),
447               (~"Thursday", 4_i32),
448               (~"Friday", 5_i32),
449               (~"Saturday", 6_i32)
450           ]) {
451             Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
452             None => Err(~"Invalid day")
453           },
454           'a' => match match_strs(s, pos, [
455               (~"Sun", 0_i32),
456               (~"Mon", 1_i32),
457               (~"Tue", 2_i32),
458               (~"Wed", 3_i32),
459               (~"Thu", 4_i32),
460               (~"Fri", 5_i32),
461               (~"Sat", 6_i32)
462           ]) {
463             Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
464             None => Err(~"Invalid day")
465           },
466           'B' => match match_strs(s, pos, [
467               (~"January", 0_i32),
468               (~"February", 1_i32),
469               (~"March", 2_i32),
470               (~"April", 3_i32),
471               (~"May", 4_i32),
472               (~"June", 5_i32),
473               (~"July", 6_i32),
474               (~"August", 7_i32),
475               (~"September", 8_i32),
476               (~"October", 9_i32),
477               (~"November", 10_i32),
478               (~"December", 11_i32)
479           ]) {
480             Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
481             None => Err(~"Invalid month")
482           },
483           'b' | 'h' => match match_strs(s, pos, [
484               (~"Jan", 0_i32),
485               (~"Feb", 1_i32),
486               (~"Mar", 2_i32),
487               (~"Apr", 3_i32),
488               (~"May", 4_i32),
489               (~"Jun", 5_i32),
490               (~"Jul", 6_i32),
491               (~"Aug", 7_i32),
492               (~"Sep", 8_i32),
493               (~"Oct", 9_i32),
494               (~"Nov", 10_i32),
495               (~"Dec", 11_i32)
496           ]) {
497             Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
498             None => Err(~"Invalid month")
499           },
500           'C' => match match_digits_in_range(s, pos, 2u, false, 0_i32,
501                                              99_i32) {
502             Some(item) => {
503                 let (v, pos) = item;
504                   tm.tm_year += (v * 100_i32) - 1900_i32;
505                   Ok(pos)
506               }
507             None => Err(~"Invalid year")
508           },
509           'c' => {
510             parse_type(s, pos, 'a', &mut *tm)
511                 .and_then(|pos| parse_char(s, pos, ' '))
512                 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
513                 .and_then(|pos| parse_char(s, pos, ' '))
514                 .and_then(|pos| parse_type(s, pos, 'e', &mut *tm))
515                 .and_then(|pos| parse_char(s, pos, ' '))
516                 .and_then(|pos| parse_type(s, pos, 'T', &mut *tm))
517                 .and_then(|pos| parse_char(s, pos, ' '))
518                 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
519           }
520           'D' | 'x' => {
521             parse_type(s, pos, 'm', &mut *tm)
522                 .and_then(|pos| parse_char(s, pos, '/'))
523                 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
524                 .and_then(|pos| parse_char(s, pos, '/'))
525                 .and_then(|pos| parse_type(s, pos, 'y', &mut *tm))
526           }
527           'd' => match match_digits_in_range(s, pos, 2u, false, 1_i32,
528                                              31_i32) {
529             Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
530             None => Err(~"Invalid day of the month")
531           },
532           'e' => match match_digits_in_range(s, pos, 2u, true, 1_i32,
533                                              31_i32) {
534             Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
535             None => Err(~"Invalid day of the month")
536           },
537           'f' => {
538             let (val, pos) = match_fractional_seconds(s, pos);
539             tm.tm_nsec = val;
540             Ok(pos)
541           }
542           'F' => {
543             parse_type(s, pos, 'Y', &mut *tm)
544                 .and_then(|pos| parse_char(s, pos, '-'))
545                 .and_then(|pos| parse_type(s, pos, 'm', &mut *tm))
546                 .and_then(|pos| parse_char(s, pos, '-'))
547                 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
548           }
549           'H' => {
550             match match_digits_in_range(s, pos, 2u, false, 0_i32, 23_i32) {
551               Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
552               None => Err(~"Invalid hour")
553             }
554           }
555           'I' => {
556             match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
557               Some(item) => {
558                   let (v, pos) = item;
559                   tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
560                   Ok(pos)
561               }
562               None => Err(~"Invalid hour")
563             }
564           }
565           'j' => {
566             match match_digits_in_range(s, pos, 3u, false, 1_i32, 366_i32) {
567               Some(item) => {
568                 let (v, pos) = item;
569                 tm.tm_yday = v - 1_i32;
570                 Ok(pos)
571               }
572               None => Err(~"Invalid day of year")
573             }
574           }
575           'k' => {
576             match match_digits_in_range(s, pos, 2u, true, 0_i32, 23_i32) {
577               Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
578               None => Err(~"Invalid hour")
579             }
580           }
581           'l' => {
582             match match_digits_in_range(s, pos, 2u, true, 1_i32, 12_i32) {
583               Some(item) => {
584                   let (v, pos) = item;
585                   tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
586                   Ok(pos)
587               }
588               None => Err(~"Invalid hour")
589             }
590           }
591           'M' => {
592             match match_digits_in_range(s, pos, 2u, false, 0_i32, 59_i32) {
593               Some(item) => { let (v, pos) = item; tm.tm_min = v; Ok(pos) }
594               None => Err(~"Invalid minute")
595             }
596           }
597           'm' => {
598             match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
599               Some(item) => {
600                 let (v, pos) = item;
601                 tm.tm_mon = v - 1_i32;
602                 Ok(pos)
603               }
604               None => Err(~"Invalid month")
605             }
606           }
607           'n' => parse_char(s, pos, '\n'),
608           'P' => match match_strs(s, pos,
609                                   [(~"am", 0_i32), (~"pm", 12_i32)]) {
610
611             Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
612             None => Err(~"Invalid hour")
613           },
614           'p' => match match_strs(s, pos,
615                                   [(~"AM", 0_i32), (~"PM", 12_i32)]) {
616
617             Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
618             None => Err(~"Invalid hour")
619           },
620           'R' => {
621             parse_type(s, pos, 'H', &mut *tm)
622                 .and_then(|pos| parse_char(s, pos, ':'))
623                 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
624           }
625           'r' => {
626             parse_type(s, pos, 'I', &mut *tm)
627                 .and_then(|pos| parse_char(s, pos, ':'))
628                 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
629                 .and_then(|pos| parse_char(s, pos, ':'))
630                 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
631                 .and_then(|pos| parse_char(s, pos, ' '))
632                 .and_then(|pos| parse_type(s, pos, 'p', &mut *tm))
633           }
634           'S' => {
635             match match_digits_in_range(s, pos, 2u, false, 0_i32, 60_i32) {
636               Some(item) => {
637                 let (v, pos) = item;
638                 tm.tm_sec = v;
639                 Ok(pos)
640               }
641               None => Err(~"Invalid second")
642             }
643           }
644           //'s' {}
645           'T' | 'X' => {
646             parse_type(s, pos, 'H', &mut *tm)
647                 .and_then(|pos| parse_char(s, pos, ':'))
648                 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
649                 .and_then(|pos| parse_char(s, pos, ':'))
650                 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
651           }
652           't' => parse_char(s, pos, '\t'),
653           'u' => {
654             match match_digits_in_range(s, pos, 1u, false, 1_i32, 7_i32) {
655               Some(item) => {
656                 let (v, pos) = item;
657                 tm.tm_wday = if v == 7 { 0 } else { v };
658                 Ok(pos)
659               }
660               None => Err(~"Invalid day of week")
661             }
662           }
663           'v' => {
664             parse_type(s, pos, 'e', &mut *tm)
665                 .and_then(|pos|  parse_char(s, pos, '-'))
666                 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
667                 .and_then(|pos| parse_char(s, pos, '-'))
668                 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
669           }
670           //'W' {}
671           'w' => {
672             match match_digits_in_range(s, pos, 1u, false, 0_i32, 6_i32) {
673               Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
674               None => Err(~"Invalid day of week")
675             }
676           }
677           'Y' => {
678             match match_digits(s, pos, 4u, false) {
679               Some(item) => {
680                 let (v, pos) = item;
681                 tm.tm_year = v - 1900_i32;
682                 Ok(pos)
683               }
684               None => Err(~"Invalid year")
685             }
686           }
687           'y' => {
688             match match_digits_in_range(s, pos, 2u, false, 0_i32, 99_i32) {
689               Some(item) => {
690                 let (v, pos) = item;
691                 tm.tm_year = v;
692                 Ok(pos)
693               }
694               None => Err(~"Invalid year")
695             }
696           }
697           'Z' => {
698             if match_str(s, pos, "UTC") || match_str(s, pos, "GMT") {
699                 tm.tm_gmtoff = 0_i32;
700                 tm.tm_zone = ~"UTC";
701                 Ok(pos + 3u)
702             } else {
703                 // It's odd, but to maintain compatibility with c's
704                 // strptime we ignore the timezone.
705                 let mut pos = pos;
706                 let len = s.len();
707                 while pos < len {
708                     let range = s.char_range_at(pos);
709                     pos = range.next;
710                     if range.ch == ' ' { break; }
711                 }
712
713                 Ok(pos)
714             }
715           }
716           'z' => {
717             let range = s.char_range_at(pos);
718
719             if range.ch == '+' || range.ch == '-' {
720                 match match_digits(s, range.next, 4u, false) {
721                   Some(item) => {
722                     let (v, pos) = item;
723                     if v == 0_i32 {
724                         tm.tm_gmtoff = 0_i32;
725                         tm.tm_zone = ~"UTC";
726                     }
727
728                     Ok(pos)
729                   }
730                   None => Err(~"Invalid zone offset")
731                 }
732             } else {
733                 Err(~"Invalid zone offset")
734             }
735           }
736           '%' => parse_char(s, pos, '%'),
737           ch => {
738             Err(format!("unknown formatting type: {}", str::from_char(ch)))
739           }
740         }
741     }
742
743     let mut rdr = BufReader::new(format.as_bytes());
744     let mut tm = Tm {
745         tm_sec: 0_i32,
746         tm_min: 0_i32,
747         tm_hour: 0_i32,
748         tm_mday: 0_i32,
749         tm_mon: 0_i32,
750         tm_year: 0_i32,
751         tm_wday: 0_i32,
752         tm_yday: 0_i32,
753         tm_isdst: 0_i32,
754         tm_gmtoff: 0_i32,
755         tm_zone: ~"",
756         tm_nsec: 0_i32,
757     };
758     let mut pos = 0u;
759     let len = s.len();
760     let mut result = Err(~"Invalid time");
761
762     while pos < len {
763         let range = s.char_range_at(pos);
764         let ch = range.ch;
765         let next = range.next;
766
767         let mut buf = [0];
768         let c = match rdr.read(buf) {
769             Some(..) => buf[0] as char,
770             None => break
771         };
772         match c {
773             '%' => {
774                 let ch = match rdr.read(buf) {
775                     Some(..) => buf[0] as char,
776                     None => break
777                 };
778                 match parse_type(s, pos, ch, &mut tm) {
779                     Ok(next) => pos = next,
780                     Err(e) => { result = Err(e); break; }
781                 }
782             },
783             c => {
784                 if c != ch { break }
785                 pos = next;
786             }
787         }
788     }
789
790     if pos == len && rdr.tell() as uint == format.len() {
791         Ok(Tm {
792             tm_sec: tm.tm_sec,
793             tm_min: tm.tm_min,
794             tm_hour: tm.tm_hour,
795             tm_mday: tm.tm_mday,
796             tm_mon: tm.tm_mon,
797             tm_year: tm.tm_year,
798             tm_wday: tm.tm_wday,
799             tm_yday: tm.tm_yday,
800             tm_isdst: tm.tm_isdst,
801             tm_gmtoff: tm.tm_gmtoff,
802             tm_zone: tm.tm_zone.clone(),
803             tm_nsec: tm.tm_nsec,
804         })
805     } else { result }
806 }
807
808 /// Formats the time according to the format string.
809 pub fn strftime(format: &str, tm: &Tm) -> ~str {
810     fn days_in_year(year: int) -> i32 {
811         if ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))) {
812             366    /* Days in a leap year */
813         } else {
814             365    /* Days in a non-leap year */
815         }
816     }
817
818     fn iso_week_days(yday: i32, wday: i32) -> int {
819         /* The number of days from the first day of the first ISO week of this
820         * year to the year day YDAY with week day WDAY.
821         * ISO weeks start on Monday. The first ISO week has the year's first
822         * Thursday.
823         * YDAY may be as small as yday_minimum.
824         */
825         let yday: int = yday as int;
826         let wday: int = wday as int;
827         let iso_week_start_wday: int = 1;                     /* Monday */
828         let iso_week1_wday: int = 4;                          /* Thursday */
829         let yday_minimum: int = 366;
830         /* Add enough to the first operand of % to make it nonnegative. */
831         let big_enough_multiple_of_7: int = (yday_minimum / 7 + 2) * 7;
832
833         yday - (yday - wday + iso_week1_wday + big_enough_multiple_of_7) % 7
834             + iso_week1_wday - iso_week_start_wday
835     }
836
837     fn iso_week(ch:char, tm: &Tm) -> ~str {
838         let mut year: int = tm.tm_year as int + 1900;
839         let mut days: int = iso_week_days (tm.tm_yday, tm.tm_wday);
840
841         if (days < 0) {
842             /* This ISO week belongs to the previous year. */
843             year -= 1;
844             days = iso_week_days (tm.tm_yday + (days_in_year(year)), tm.tm_wday);
845         } else {
846             let d: int = iso_week_days (tm.tm_yday - (days_in_year(year)),
847                                         tm.tm_wday);
848             if (0 <= d) {
849                 /* This ISO week belongs to the next year. */
850                 year += 1;
851                 days = d;
852             }
853         }
854
855         match ch {
856             'G' => format!("{}", year),
857             'g' => format!("{:02d}", (year % 100 + 100) % 100),
858             'V' => format!("{:02d}", days / 7 + 1),
859             _ => ~""
860         }
861     }
862
863     fn parse_type(ch: char, tm: &Tm) -> ~str {
864       let die = || format!("strftime: can't understand this format {} ", ch);
865         match ch {
866           'A' => match tm.tm_wday as int {
867             0 => ~"Sunday",
868             1 => ~"Monday",
869             2 => ~"Tuesday",
870             3 => ~"Wednesday",
871             4 => ~"Thursday",
872             5 => ~"Friday",
873             6 => ~"Saturday",
874             _ => die()
875           },
876          'a' => match tm.tm_wday as int {
877             0 => ~"Sun",
878             1 => ~"Mon",
879             2 => ~"Tue",
880             3 => ~"Wed",
881             4 => ~"Thu",
882             5 => ~"Fri",
883             6 => ~"Sat",
884             _ => die()
885           },
886           'B' => match tm.tm_mon as int {
887             0 => ~"January",
888             1 => ~"February",
889             2 => ~"March",
890             3 => ~"April",
891             4 => ~"May",
892             5 => ~"June",
893             6 => ~"July",
894             7 => ~"August",
895             8 => ~"September",
896             9 => ~"October",
897             10 => ~"November",
898             11 => ~"December",
899             _ => die()
900           },
901           'b' | 'h' => match tm.tm_mon as int {
902             0 => ~"Jan",
903             1 => ~"Feb",
904             2 => ~"Mar",
905             3 => ~"Apr",
906             4 => ~"May",
907             5 => ~"Jun",
908             6 => ~"Jul",
909             7 => ~"Aug",
910             8 => ~"Sep",
911             9 => ~"Oct",
912             10 => ~"Nov",
913             11 => ~"Dec",
914             _  => die()
915           },
916           'C' => format!("{:02d}", (tm.tm_year as int + 1900) / 100),
917           'c' => {
918             format!("{} {} {} {} {}",
919                 parse_type('a', tm),
920                 parse_type('b', tm),
921                 parse_type('e', tm),
922                 parse_type('T', tm),
923                 parse_type('Y', tm))
924           }
925           'D' | 'x' => {
926             format!("{}/{}/{}",
927                 parse_type('m', tm),
928                 parse_type('d', tm),
929                 parse_type('y', tm))
930           }
931           'd' => format!("{:02d}", tm.tm_mday),
932           'e' => format!("{:2d}", tm.tm_mday),
933           'f' => format!("{:09d}", tm.tm_nsec),
934           'F' => {
935             format!("{}-{}-{}",
936                 parse_type('Y', tm),
937                 parse_type('m', tm),
938                 parse_type('d', tm))
939           }
940           'G' => iso_week('G', tm),
941           'g' => iso_week('g', tm),
942           'H' => format!("{:02d}", tm.tm_hour),
943           'I' => {
944             let mut h = tm.tm_hour;
945             if h == 0 { h = 12 }
946             if h > 12 { h -= 12 }
947             format!("{:02d}", h)
948           }
949           'j' => format!("{:03d}", tm.tm_yday + 1),
950           'k' => format!("{:2d}", tm.tm_hour),
951           'l' => {
952             let mut h = tm.tm_hour;
953             if h == 0 { h = 12 }
954             if h > 12 { h -= 12 }
955             format!("{:2d}", h)
956           }
957           'M' => format!("{:02d}", tm.tm_min),
958           'm' => format!("{:02d}", tm.tm_mon + 1),
959           'n' => ~"\n",
960           'P' => if (tm.tm_hour as int) < 12 { ~"am" } else { ~"pm" },
961           'p' => if (tm.tm_hour as int) < 12 { ~"AM" } else { ~"PM" },
962           'R' => {
963             format!("{}:{}",
964                 parse_type('H', tm),
965                 parse_type('M', tm))
966           }
967           'r' => {
968             format!("{}:{}:{} {}",
969                 parse_type('I', tm),
970                 parse_type('M', tm),
971                 parse_type('S', tm),
972                 parse_type('p', tm))
973           }
974           'S' => format!("{:02d}", tm.tm_sec),
975           's' => format!("{}", tm.to_timespec().sec),
976           'T' | 'X' => {
977             format!("{}:{}:{}",
978                 parse_type('H', tm),
979                 parse_type('M', tm),
980                 parse_type('S', tm))
981           }
982           't' => ~"\t",
983           'U' => format!("{:02d}", (tm.tm_yday - tm.tm_wday + 7) / 7),
984           'u' => {
985             let i = tm.tm_wday as int;
986             (if i == 0 { 7 } else { i }).to_str()
987           }
988           'V' => iso_week('V', tm),
989           'v' => {
990             format!("{}-{}-{}",
991                 parse_type('e', tm),
992                 parse_type('b', tm),
993                 parse_type('Y', tm))
994           }
995           'W' => format!("{:02d}", (tm.tm_yday - (tm.tm_wday - 1 + 7) % 7 + 7)
996                          / 7),
997           'w' => (tm.tm_wday as int).to_str(),
998           'Y' => (tm.tm_year as int + 1900).to_str(),
999           'y' => format!("{:02d}", (tm.tm_year as int + 1900) % 100),
1000           'Z' => tm.tm_zone.clone(),
1001           'z' => {
1002             let sign = if tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
1003             let mut m = num::abs(tm.tm_gmtoff) / 60_i32;
1004             let h = m / 60_i32;
1005             m -= h * 60_i32;
1006             format!("{}{:02d}{:02d}", sign, h, m)
1007           }
1008           '+' => tm.rfc3339(),
1009           '%' => ~"%",
1010           _   => die()
1011         }
1012     }
1013
1014     let mut buf = ~[];
1015
1016     let mut rdr = BufReader::new(format.as_bytes());
1017     loop {
1018         let mut b = [0];
1019         let ch = match rdr.read(b) {
1020             Some(..) => b[0],
1021             None => break,
1022         };
1023         match ch as char {
1024             '%' => {
1025                 rdr.read(b);
1026                 let s = parse_type(b[0] as char, tm);
1027                 buf.push_all(s.as_bytes());
1028             }
1029             ch => buf.push(ch as u8)
1030         }
1031     }
1032
1033     str::from_utf8_owned(buf)
1034 }
1035
1036 #[cfg(test)]
1037 mod tests {
1038     use super::*;
1039
1040     use std::f64;
1041     use std::result::{Err, Ok};
1042
1043     #[cfg(windows)]
1044     fn set_time_zone() {
1045         use std::libc;
1046         // Windows crt doesn't see any environment variable set by
1047         // `SetEnvironmentVariable`, which `os::setenv` internally uses.
1048         // It is why we use `putenv` here.
1049         extern {
1050             fn _putenv(envstring: *libc::c_char) -> libc::c_int;
1051         }
1052
1053         unsafe {
1054             // Windows does not understand "America/Los_Angeles".
1055             // PST+08 may look wrong, but not! "PST" indicates
1056             // the name of timezone. "+08" means UTC = local + 08.
1057             "TZ=PST+08".with_c_str(|env| {
1058                 _putenv(env);
1059             })
1060         }
1061         tzset();
1062     }
1063     #[cfg(not(windows))]
1064     fn set_time_zone() {
1065         use std::os;
1066         os::setenv("TZ", "America/Los_Angeles");
1067         tzset();
1068     }
1069
1070     fn test_get_time() {
1071         static SOME_RECENT_DATE: i64 = 1325376000i64; // 2012-01-01T00:00:00Z
1072         static SOME_FUTURE_DATE: i64 = 1577836800i64; // 2020-01-01T00:00:00Z
1073
1074         let tv1 = get_time();
1075         debug!("tv1={:?} sec + {:?} nsec", tv1.sec as uint, tv1.nsec as uint);
1076
1077         assert!(tv1.sec > SOME_RECENT_DATE);
1078         assert!(tv1.nsec < 1000000000i32);
1079
1080         let tv2 = get_time();
1081         debug!("tv2={:?} sec + {:?} nsec", tv2.sec as uint, tv2.nsec as uint);
1082
1083         assert!(tv2.sec >= tv1.sec);
1084         assert!(tv2.sec < SOME_FUTURE_DATE);
1085         assert!(tv2.nsec < 1000000000i32);
1086         if tv2.sec == tv1.sec {
1087             assert!(tv2.nsec >= tv1.nsec);
1088         }
1089     }
1090
1091     fn test_precise_time() {
1092         let s0 = precise_time_s();
1093         debug!("s0={} sec", f64::to_str_digits(s0, 9u));
1094         assert!(s0 > 0.);
1095
1096         let ns0 = precise_time_ns();
1097         let ns1 = precise_time_ns();
1098         debug!("ns0={:?} ns", ns0);
1099         debug!("ns1={:?} ns", ns1);
1100         assert!(ns1 >= ns0);
1101
1102         let ns2 = precise_time_ns();
1103         debug!("ns2={:?} ns", ns2);
1104         assert!(ns2 >= ns1);
1105     }
1106
1107     fn test_at_utc() {
1108         set_time_zone();
1109
1110         let time = Timespec::new(1234567890, 54321);
1111         let utc = at_utc(time);
1112
1113         assert_eq!(utc.tm_sec, 30_i32);
1114         assert_eq!(utc.tm_min, 31_i32);
1115         assert_eq!(utc.tm_hour, 23_i32);
1116         assert_eq!(utc.tm_mday, 13_i32);
1117         assert_eq!(utc.tm_mon, 1_i32);
1118         assert_eq!(utc.tm_year, 109_i32);
1119         assert_eq!(utc.tm_wday, 5_i32);
1120         assert_eq!(utc.tm_yday, 43_i32);
1121         assert_eq!(utc.tm_isdst, 0_i32);
1122         assert_eq!(utc.tm_gmtoff, 0_i32);
1123         assert_eq!(utc.tm_zone, ~"UTC");
1124         assert_eq!(utc.tm_nsec, 54321_i32);
1125     }
1126
1127     fn test_at() {
1128         set_time_zone();
1129
1130         let time = Timespec::new(1234567890, 54321);
1131         let local = at(time);
1132
1133         error!("time_at: {:?}", local);
1134
1135         assert_eq!(local.tm_sec, 30_i32);
1136         assert_eq!(local.tm_min, 31_i32);
1137         assert_eq!(local.tm_hour, 15_i32);
1138         assert_eq!(local.tm_mday, 13_i32);
1139         assert_eq!(local.tm_mon, 1_i32);
1140         assert_eq!(local.tm_year, 109_i32);
1141         assert_eq!(local.tm_wday, 5_i32);
1142         assert_eq!(local.tm_yday, 43_i32);
1143         assert_eq!(local.tm_isdst, 0_i32);
1144         assert_eq!(local.tm_gmtoff, -28800_i32);
1145
1146         // FIXME (#2350): We should probably standardize on the timezone
1147         // abbreviation.
1148         let zone = &local.tm_zone;
1149         assert!(*zone == ~"PST" || *zone == ~"Pacific Standard Time");
1150
1151         assert_eq!(local.tm_nsec, 54321_i32);
1152     }
1153
1154     fn test_to_timespec() {
1155         set_time_zone();
1156
1157         let time = Timespec::new(1234567890, 54321);
1158         let utc = at_utc(time);
1159
1160         assert_eq!(utc.to_timespec(), time);
1161         assert_eq!(utc.to_local().to_timespec(), time);
1162     }
1163
1164     fn test_conversions() {
1165         set_time_zone();
1166
1167         let time = Timespec::new(1234567890, 54321);
1168         let utc = at_utc(time);
1169         let local = at(time);
1170
1171         assert!(local.to_local() == local);
1172         assert!(local.to_utc() == utc);
1173         assert!(local.to_utc().to_local() == local);
1174         assert!(utc.to_utc() == utc);
1175         assert!(utc.to_local() == local);
1176         assert!(utc.to_local().to_utc() == utc);
1177     }
1178
1179     fn test_strptime() {
1180         set_time_zone();
1181
1182         match strptime("", "") {
1183           Ok(ref tm) => {
1184             assert!(tm.tm_sec == 0_i32);
1185             assert!(tm.tm_min == 0_i32);
1186             assert!(tm.tm_hour == 0_i32);
1187             assert!(tm.tm_mday == 0_i32);
1188             assert!(tm.tm_mon == 0_i32);
1189             assert!(tm.tm_year == 0_i32);
1190             assert!(tm.tm_wday == 0_i32);
1191             assert!(tm.tm_isdst == 0_i32);
1192             assert!(tm.tm_gmtoff == 0_i32);
1193             assert!(tm.tm_zone == ~"");
1194             assert!(tm.tm_nsec == 0_i32);
1195           }
1196           Err(_) => ()
1197         }
1198
1199         let format = "%a %b %e %T.%f %Y";
1200         assert_eq!(strptime("", format), Err(~"Invalid time"));
1201         assert!(strptime("Fri Feb 13 15:31:30", format)
1202             == Err(~"Invalid time"));
1203
1204         match strptime("Fri Feb 13 15:31:30.01234 2009", format) {
1205           Err(e) => fail!(e),
1206           Ok(ref tm) => {
1207             assert!(tm.tm_sec == 30_i32);
1208             assert!(tm.tm_min == 31_i32);
1209             assert!(tm.tm_hour == 15_i32);
1210             assert!(tm.tm_mday == 13_i32);
1211             assert!(tm.tm_mon == 1_i32);
1212             assert!(tm.tm_year == 109_i32);
1213             assert!(tm.tm_wday == 5_i32);
1214             assert!(tm.tm_yday == 0_i32);
1215             assert!(tm.tm_isdst == 0_i32);
1216             assert!(tm.tm_gmtoff == 0_i32);
1217             assert!(tm.tm_zone == ~"");
1218             assert!(tm.tm_nsec == 12340000_i32);
1219           }
1220         }
1221
1222         fn test(s: &str, format: &str) -> bool {
1223             match strptime(s, format) {
1224               Ok(ref tm) => tm.strftime(format) == s.to_owned(),
1225               Err(e) => fail!(e)
1226             }
1227         }
1228
1229         let days = [
1230             ~"Sunday",
1231             ~"Monday",
1232             ~"Tuesday",
1233             ~"Wednesday",
1234             ~"Thursday",
1235             ~"Friday",
1236             ~"Saturday"
1237         ];
1238         for day in days.iter() {
1239             assert!(test(*day, "%A"));
1240         }
1241
1242         let days = [
1243             ~"Sun",
1244             ~"Mon",
1245             ~"Tue",
1246             ~"Wed",
1247             ~"Thu",
1248             ~"Fri",
1249             ~"Sat"
1250         ];
1251         for day in days.iter() {
1252             assert!(test(*day, "%a"));
1253         }
1254
1255         let months = [
1256             ~"January",
1257             ~"February",
1258             ~"March",
1259             ~"April",
1260             ~"May",
1261             ~"June",
1262             ~"July",
1263             ~"August",
1264             ~"September",
1265             ~"October",
1266             ~"November",
1267             ~"December"
1268         ];
1269         for day in months.iter() {
1270             assert!(test(*day, "%B"));
1271         }
1272
1273         let months = [
1274             ~"Jan",
1275             ~"Feb",
1276             ~"Mar",
1277             ~"Apr",
1278             ~"May",
1279             ~"Jun",
1280             ~"Jul",
1281             ~"Aug",
1282             ~"Sep",
1283             ~"Oct",
1284             ~"Nov",
1285             ~"Dec"
1286         ];
1287         for day in months.iter() {
1288             assert!(test(*day, "%b"));
1289         }
1290
1291         assert!(test("19", "%C"));
1292         assert!(test("Fri Feb 13 23:31:30 2009", "%c"));
1293         assert!(test("02/13/09", "%D"));
1294         assert!(test("03", "%d"));
1295         assert!(test("13", "%d"));
1296         assert!(test(" 3", "%e"));
1297         assert!(test("13", "%e"));
1298         assert!(test("2009-02-13", "%F"));
1299         assert!(test("03", "%H"));
1300         assert!(test("13", "%H"));
1301         assert!(test("03", "%I")); // FIXME (#2350): flesh out
1302         assert!(test("11", "%I")); // FIXME (#2350): flesh out
1303         assert!(test("044", "%j"));
1304         assert!(test(" 3", "%k"));
1305         assert!(test("13", "%k"));
1306         assert!(test(" 1", "%l"));
1307         assert!(test("11", "%l"));
1308         assert!(test("03", "%M"));
1309         assert!(test("13", "%M"));
1310         assert!(test("\n", "%n"));
1311         assert!(test("am", "%P"));
1312         assert!(test("pm", "%P"));
1313         assert!(test("AM", "%p"));
1314         assert!(test("PM", "%p"));
1315         assert!(test("23:31", "%R"));
1316         assert!(test("11:31:30 AM", "%r"));
1317         assert!(test("11:31:30 PM", "%r"));
1318         assert!(test("03", "%S"));
1319         assert!(test("13", "%S"));
1320         assert!(test("15:31:30", "%T"));
1321         assert!(test("\t", "%t"));
1322         assert!(test("1", "%u"));
1323         assert!(test("7", "%u"));
1324         assert!(test("13-Feb-2009", "%v"));
1325         assert!(test("0", "%w"));
1326         assert!(test("6", "%w"));
1327         assert!(test("2009", "%Y"));
1328         assert!(test("09", "%y"));
1329         assert!(strptime("UTC", "%Z").unwrap().tm_zone ==
1330             ~"UTC");
1331         assert!(strptime("PST", "%Z").unwrap().tm_zone ==
1332             ~"");
1333         assert!(strptime("-0000", "%z").unwrap().tm_gmtoff ==
1334             0);
1335         assert!(strptime("-0800", "%z").unwrap().tm_gmtoff ==
1336             0);
1337         assert!(test("%", "%%"));
1338
1339         // Test for #7256
1340         assert_eq!(strptime("360", "%Y-%m-%d"), Err(~"Invalid year"))
1341     }
1342
1343     fn test_ctime() {
1344         set_time_zone();
1345
1346         let time = Timespec::new(1234567890, 54321);
1347         let utc   = at_utc(time);
1348         let local = at(time);
1349
1350         error!("test_ctime: {:?} {:?}", utc.ctime(), local.ctime());
1351
1352         assert_eq!(utc.ctime(), ~"Fri Feb 13 23:31:30 2009");
1353         assert_eq!(local.ctime(), ~"Fri Feb 13 15:31:30 2009");
1354     }
1355
1356     fn test_strftime() {
1357         set_time_zone();
1358
1359         let time = Timespec::new(1234567890, 54321);
1360         let utc = at_utc(time);
1361         let local = at(time);
1362
1363         assert_eq!(local.strftime(""), ~"");
1364         assert_eq!(local.strftime("%A"), ~"Friday");
1365         assert_eq!(local.strftime("%a"), ~"Fri");
1366         assert_eq!(local.strftime("%B"), ~"February");
1367         assert_eq!(local.strftime("%b"), ~"Feb");
1368         assert_eq!(local.strftime("%C"), ~"20");
1369         assert_eq!(local.strftime("%c"), ~"Fri Feb 13 15:31:30 2009");
1370         assert_eq!(local.strftime("%D"), ~"02/13/09");
1371         assert_eq!(local.strftime("%d"), ~"13");
1372         assert_eq!(local.strftime("%e"), ~"13");
1373         assert_eq!(local.strftime("%f"), ~"000054321");
1374         assert_eq!(local.strftime("%F"), ~"2009-02-13");
1375         assert_eq!(local.strftime("%G"), ~"2009");
1376         assert_eq!(local.strftime("%g"), ~"09");
1377         assert_eq!(local.strftime("%H"), ~"15");
1378         assert_eq!(local.strftime("%I"), ~"03");
1379         assert_eq!(local.strftime("%j"), ~"044");
1380         assert_eq!(local.strftime("%k"), ~"15");
1381         assert_eq!(local.strftime("%l"), ~" 3");
1382         assert_eq!(local.strftime("%M"), ~"31");
1383         assert_eq!(local.strftime("%m"), ~"02");
1384         assert_eq!(local.strftime("%n"), ~"\n");
1385         assert_eq!(local.strftime("%P"), ~"pm");
1386         assert_eq!(local.strftime("%p"), ~"PM");
1387         assert_eq!(local.strftime("%R"), ~"15:31");
1388         assert_eq!(local.strftime("%r"), ~"03:31:30 PM");
1389         assert_eq!(local.strftime("%S"), ~"30");
1390         assert_eq!(local.strftime("%s"), ~"1234567890");
1391         assert_eq!(local.strftime("%T"), ~"15:31:30");
1392         assert_eq!(local.strftime("%t"), ~"\t");
1393         assert_eq!(local.strftime("%U"), ~"06");
1394         assert_eq!(local.strftime("%u"), ~"5");
1395         assert_eq!(local.strftime("%V"), ~"07");
1396         assert_eq!(local.strftime("%v"), ~"13-Feb-2009");
1397         assert_eq!(local.strftime("%W"), ~"06");
1398         assert_eq!(local.strftime("%w"), ~"5");
1399         assert_eq!(local.strftime("%X"), ~"15:31:30"); // FIXME (#2350): support locale
1400         assert_eq!(local.strftime("%x"), ~"02/13/09"); // FIXME (#2350): support locale
1401         assert_eq!(local.strftime("%Y"), ~"2009");
1402         assert_eq!(local.strftime("%y"), ~"09");
1403         assert_eq!(local.strftime("%+"), ~"2009-02-13T15:31:30-08:00");
1404
1405         // FIXME (#2350): We should probably standardize on the timezone
1406         // abbreviation.
1407         let zone = local.strftime("%Z");
1408         assert!(zone == ~"PST" || zone == ~"Pacific Standard Time");
1409
1410         assert_eq!(local.strftime("%z"), ~"-0800");
1411         assert_eq!(local.strftime("%%"), ~"%");
1412
1413         // FIXME (#2350): We should probably standardize on the timezone
1414         // abbreviation.
1415         let rfc822 = local.rfc822();
1416         let prefix = ~"Fri, 13 Feb 2009 15:31:30 ";
1417         assert!(rfc822 == prefix + "PST" || rfc822 == prefix + "Pacific Standard Time");
1418
1419         assert_eq!(local.ctime(), ~"Fri Feb 13 15:31:30 2009");
1420         assert_eq!(local.rfc822z(), ~"Fri, 13 Feb 2009 15:31:30 -0800");
1421         assert_eq!(local.rfc3339(), ~"2009-02-13T15:31:30-08:00");
1422
1423         assert_eq!(utc.ctime(), ~"Fri Feb 13 23:31:30 2009");
1424         assert_eq!(utc.rfc822(), ~"Fri, 13 Feb 2009 23:31:30 GMT");
1425         assert_eq!(utc.rfc822z(), ~"Fri, 13 Feb 2009 23:31:30 -0000");
1426         assert_eq!(utc.rfc3339(), ~"2009-02-13T23:31:30Z");
1427     }
1428
1429     fn test_timespec_eq_ord() {
1430         let a = &Timespec::new(-2, 1);
1431         let b = &Timespec::new(-1, 2);
1432         let c = &Timespec::new(1, 2);
1433         let d = &Timespec::new(2, 1);
1434         let e = &Timespec::new(2, 1);
1435
1436         assert!(d.eq(e));
1437         assert!(c.ne(e));
1438
1439         assert!(a.lt(b));
1440         assert!(b.lt(c));
1441         assert!(c.lt(d));
1442
1443         assert!(a.le(b));
1444         assert!(b.le(c));
1445         assert!(c.le(d));
1446         assert!(d.le(e));
1447         assert!(e.le(d));
1448
1449         assert!(b.ge(a));
1450         assert!(c.ge(b));
1451         assert!(d.ge(c));
1452         assert!(e.ge(d));
1453         assert!(d.ge(e));
1454
1455         assert!(b.gt(a));
1456         assert!(c.gt(b));
1457         assert!(d.gt(c));
1458     }
1459
1460     #[test]
1461     #[ignore(cfg(target_os = "android"))] // FIXME #10958
1462     fn run_tests() {
1463         // The tests race on tzset. So instead of having many independent
1464         // tests, we will just call the functions now.
1465         test_get_time();
1466         test_precise_time();
1467         test_at_utc();
1468         test_at();
1469         test_to_timespec();
1470         test_conversions();
1471         test_strptime();
1472         test_ctime();
1473         test_strftime();
1474         test_timespec_eq_ord();
1475     }
1476 }