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.
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.
11 //! Simple time handling.
13 #![crate_name = "time"]
16 #![crate_type = "rlib"]
17 #![crate_type = "dylib"]
18 #![license = "MIT/ASL2"]
19 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
20 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
21 html_root_url = "http://doc.rust-lang.org/master/",
22 html_playground_url = "http://play.rust-lang.org/")]
25 #[cfg(test)] extern crate debug;
26 #[cfg(test)] #[phase(plugin, link)] extern crate log;
28 extern crate serialize;
31 use std::io::BufReader;
33 use std::string::String;
34 use std::time::Duration;
36 static NSEC_PER_SEC: i32 = 1_000_000_000_i32;
43 pub fn rust_gmtime(sec: i64, nsec: i32, result: &mut Tm);
44 pub fn rust_localtime(sec: i64, nsec: i32, result: &mut Tm);
45 pub fn rust_timegm(tm: &Tm) -> i64;
46 pub fn rust_mktime(tm: &Tm) -> i64;
50 #[cfg(unix, not(target_os = "macos"), not(target_os = "ios"))]
52 use libc::{c_int, timespec};
54 // Apparently android provides this in some other library?
55 #[cfg(not(target_os = "android"))]
60 pub fn clock_gettime(clk_id: c_int, tp: *mut timespec) -> c_int;
64 #[cfg(target_os = "macos")]
65 #[cfg(target_os = "ios")]
67 use libc::{timeval, timezone, c_int, mach_timebase_info};
70 pub fn gettimeofday(tp: *mut timeval, tzp: *mut timezone) -> c_int;
71 pub fn mach_absolute_time() -> u64;
72 pub fn mach_timebase_info(info: *mut mach_timebase_info) -> c_int;
76 /// A record specifying a time value in seconds and nanoseconds.
77 #[deriving(Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Show)]
78 pub struct Timespec { pub sec: i64, pub nsec: i32 }
80 * Timespec assumes that pre-epoch Timespecs have negative sec and positive
81 * nsec fields. Darwin's and Linux's struct timespec functions handle pre-
82 * epoch timestamps using a "two steps back, one step forward" representation,
83 * though the man pages do not actually document this. For example, the time
84 * -1.2 seconds before the epoch is represented by `Timespec { sec: -2_i64,
85 * nsec: 800_000_000_i32 }`.
88 pub fn new(sec: i64, nsec: i32) -> Timespec {
89 assert!(nsec >= 0 && nsec < NSEC_PER_SEC);
90 Timespec { sec: sec, nsec: nsec }
94 impl Add<Duration, Timespec> for Timespec {
95 fn add(&self, other: &Duration) -> Timespec {
96 let d_sec = other.num_seconds();
97 // It is safe to unwrap the nanoseconds, because there cannot be
98 // more than one second left, which fits in i64 and in i32.
99 let d_nsec = (other - Duration::seconds(d_sec))
100 .num_nanoseconds().unwrap() as i32;
101 let mut sec = self.sec + d_sec;
102 let mut nsec = self.nsec + d_nsec;
103 if nsec >= NSEC_PER_SEC {
104 nsec -= NSEC_PER_SEC;
107 nsec += NSEC_PER_SEC;
110 Timespec::new(sec, nsec)
114 impl Sub<Timespec, Duration> for Timespec {
115 fn sub(&self, other: &Timespec) -> Duration {
116 let sec = self.sec - other.sec;
117 let nsec = self.nsec - other.nsec;
118 Duration::seconds(sec) + Duration::nanoseconds(nsec as i64)
123 * Returns the current time as a `timespec` containing the seconds and
124 * nanoseconds since 1970-01-01T00:00:00Z.
126 pub fn get_time() -> Timespec {
128 let (sec, nsec) = os_get_time();
129 return Timespec::new(sec, nsec);
133 unsafe fn os_get_time() -> (i64, i32) {
134 static NANOSECONDS_FROM_1601_TO_1970: u64 = 11644473600000000;
136 let mut time = libc::FILETIME {
140 libc::GetSystemTimeAsFileTime(&mut time);
142 // A FILETIME contains a 64-bit value representing the number of
143 // hectonanosecond (100-nanosecond) intervals since 1601-01-01T00:00:00Z.
144 // http://support.microsoft.com/kb/167296/en-us
145 let ns_since_1601 = ((time.dwHighDateTime as u64 << 32) |
146 (time.dwLowDateTime as u64 << 0)) / 10;
147 let ns_since_1970 = ns_since_1601 - NANOSECONDS_FROM_1601_TO_1970;
149 ((ns_since_1970 / 1000000) as i64,
150 ((ns_since_1970 % 1000000) * 1000) as i32)
153 #[cfg(target_os = "macos")]
154 #[cfg(target_os = "ios")]
155 unsafe fn os_get_time() -> (i64, i32) {
157 let mut tv = libc::timeval { tv_sec: 0, tv_usec: 0 };
158 imp::gettimeofday(&mut tv, ptr::null_mut());
159 (tv.tv_sec as i64, tv.tv_usec * 1000)
162 #[cfg(not(target_os = "macos"), not(target_os = "ios"), not(windows))]
163 unsafe fn os_get_time() -> (i64, i32) {
164 let mut tv = libc::timespec { tv_sec: 0, tv_nsec: 0 };
165 imp::clock_gettime(libc::CLOCK_REALTIME, &mut tv);
166 (tv.tv_sec as i64, tv.tv_nsec as i32)
172 * Returns the current value of a high-resolution performance counter
173 * in nanoseconds since an unspecified epoch.
175 pub fn precise_time_ns() -> u64 {
176 return os_precise_time_ns();
179 fn os_precise_time_ns() -> u64 {
180 let mut ticks_per_s = 0;
182 libc::QueryPerformanceFrequency(&mut ticks_per_s)
184 let ticks_per_s = if ticks_per_s == 0 {1} else {ticks_per_s};
187 libc::QueryPerformanceCounter(&mut ticks)
190 return (ticks as u64 * 1000000000) / (ticks_per_s as u64);
193 #[cfg(target_os = "macos")]
194 #[cfg(target_os = "ios")]
195 fn os_precise_time_ns() -> u64 {
196 static mut TIMEBASE: libc::mach_timebase_info = libc::mach_timebase_info { numer: 0,
198 static mut ONCE: std::sync::Once = std::sync::ONCE_INIT;
201 imp::mach_timebase_info(&mut TIMEBASE);
203 let time = imp::mach_absolute_time();
204 time * TIMEBASE.numer as u64 / TIMEBASE.denom as u64
208 #[cfg(not(windows), not(target_os = "macos"), not(target_os = "ios"))]
209 fn os_precise_time_ns() -> u64 {
210 let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
212 imp::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts);
214 return (ts.tv_sec as u64) * 1000000000 + (ts.tv_nsec as u64)
220 * Returns the current value of a high-resolution performance counter
221 * in seconds since an unspecified epoch.
223 pub fn precise_time_s() -> f64 {
224 return (precise_time_ns() as f64) / 1000000000.;
229 rustrt::rust_tzset();
233 /// Holds a calendar date and time broken down into its components (year, month, day, and so on),
234 /// also called a broken-down time value.
235 // FIXME: use c_int instead of i32?
237 #[deriving(Clone, PartialEq, Eq, Show)]
239 /// Seconds after the minute - [0, 60]
242 /// Minutes after the hour - [0, 59]
245 /// Hours after midnight - [0, 23]
248 /// Day of the month - [1, 31]
251 /// Months since January - [0, 11]
257 /// Days since Sunday - [0, 6]. 0 = Sunday, 1 = Monday, ..., 6 = Saturday.
260 /// Days since January 1 - [0, 365]
263 /// Daylight Saving Time flag.
265 /// This value is positive if Daylight Saving Time is in effect, zero if Daylight Saving Time
266 /// is not in effect, and negative if this information is not available.
269 /// Identifies the time zone that was used to compute this broken-down time value, including any
270 /// adjustment for Daylight Saving Time. This is the number of seconds east of UTC. For example,
271 /// for U.S. Pacific Daylight Time, the value is -7*60*60 = -25200.
274 /// Nanoseconds after the second - [0, 10<sup>9</sup> - 1]
278 pub fn empty_tm() -> Tm {
294 /// Returns the specified time in UTC
295 pub fn at_utc(clock: Timespec) -> Tm {
297 let Timespec { sec, nsec } = clock;
298 let mut tm = empty_tm();
299 rustrt::rust_gmtime(sec, nsec, &mut tm);
304 /// Returns the current time in UTC
305 pub fn now_utc() -> Tm {
309 /// Returns the specified time in the local timezone
310 pub fn at(clock: Timespec) -> Tm {
312 let Timespec { sec, nsec } = clock;
313 let mut tm = empty_tm();
314 rustrt::rust_localtime(sec, nsec, &mut tm);
319 /// Returns the current time in the local timezone
326 /// Convert time to the seconds from January 1, 1970
327 pub fn to_timespec(&self) -> Timespec {
329 let sec = match self.tm_gmtoff {
330 0_i32 => rustrt::rust_timegm(self),
331 _ => rustrt::rust_mktime(self)
334 Timespec::new(sec, self.tm_nsec)
338 /// Convert time to the local timezone
339 pub fn to_local(&self) -> Tm {
340 at(self.to_timespec())
343 /// Convert time to the UTC
344 pub fn to_utc(&self) -> Tm {
345 at_utc(self.to_timespec())
349 * Returns a time string formatted according to the `asctime` format in ISO
350 * C, in the local timezone.
352 * Example: "Thu Jan 1 00:00:00 1970"
354 pub fn ctime(&self) -> String {
355 self.to_local().asctime()
359 * Returns a time string formatted according to the `asctime` format in ISO
362 * Example: "Thu Jan 1 00:00:00 1970"
364 pub fn asctime(&self) -> String {
368 /// Formats the time according to the format string.
369 pub fn strftime(&self, format: &str) -> String {
370 strftime(format, self)
374 * Returns a time string formatted according to RFC 822.
376 * local: "Thu, 22 Mar 2012 07:53:18 PST"
377 * utc: "Thu, 22 Mar 2012 14:53:18 GMT"
379 pub fn rfc822(&self) -> String {
380 if self.tm_gmtoff == 0_i32 {
381 self.strftime("%a, %d %b %Y %T GMT")
383 self.strftime("%a, %d %b %Y %T %Z")
388 * Returns a time string formatted according to RFC 822 with Zulu time.
390 * local: "Thu, 22 Mar 2012 07:53:18 -0700"
391 * utc: "Thu, 22 Mar 2012 14:53:18 -0000"
393 pub fn rfc822z(&self) -> String {
394 self.strftime("%a, %d %b %Y %T %z")
398 * Returns a time string formatted according to RFC 3339. RFC 3339 is
399 * compatible with ISO 8601.
401 * local: "2012-02-22T07:53:18-07:00"
402 * utc: "2012-02-22T14:53:18Z"
404 pub fn rfc3339(&self) -> String {
405 if self.tm_gmtoff == 0_i32 {
406 self.strftime("%Y-%m-%dT%H:%M:%SZ")
408 let s = self.strftime("%Y-%m-%dT%H:%M:%S");
409 let sign = if self.tm_gmtoff > 0_i32 { '+' } else { '-' };
410 let mut m = num::abs(self.tm_gmtoff) / 60_i32;
413 format!("{}{}{:02d}:{:02d}", s, sign, h as int, m as int)
418 /// Parses the time from the string according to the format string.
419 pub fn strptime(s: &str, format: &str) -> Result<Tm, String> {
420 fn match_str(s: &str, pos: uint, needle: &str) -> bool {
421 return s.slice_from(pos).starts_with(needle);
424 fn match_strs(ss: &str, pos: uint, strs: &[(&str, i32)])
425 -> Option<(i32, uint)> {
426 for &(needle, value) in strs.iter() {
427 if match_str(ss, pos, needle) {
428 return Some((value, pos + needle.len()));
435 fn match_digits(ss: &str, pos: uint, digits: uint, ws: bool)
436 -> Option<(i32, uint)> {
439 let mut value = 0_i32;
446 let range = ss.char_range_at(pos);
451 value = value * 10_i32 + (range.ch as i32 - '0' as i32);
462 fn match_fractional_seconds(ss: &str, pos: uint) -> (i32, uint) {
464 let mut value = 0_i32;
465 let mut multiplier = NSEC_PER_SEC / 10;
472 let range = ss.char_range_at(pos);
477 // This will drop digits after the nanoseconds place
478 let digit = range.ch as i32 - '0' as i32;
479 value += digit * multiplier;
489 fn match_digits_in_range(ss: &str, pos: uint, digits: uint, ws: bool,
490 min: i32, max: i32) -> Option<(i32, uint)> {
491 match match_digits(ss, pos, digits, ws) {
492 Some((val, pos)) if val >= min && val <= max => {
499 fn parse_char(s: &str, pos: uint, c: char) -> Result<uint, String> {
500 let range = s.char_range_at(pos);
505 Err(format!("Expected {}, found {}", c, range.ch))
509 fn parse_type(s: &str, pos: uint, ch: char, tm: &mut Tm)
510 -> Result<uint, String> {
512 'A' => match match_strs(s, pos, [
516 ("Wednesday", 3_i32),
521 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
522 None => Err("Invalid day".to_string())
524 'a' => match match_strs(s, pos, [
533 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
534 None => Err("Invalid day".to_string())
536 'B' => match match_strs(s, pos, [
545 ("September", 8_i32),
547 ("November", 10_i32),
550 Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
551 None => Err("Invalid month".to_string())
553 'b' | 'h' => match match_strs(s, pos, [
567 Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
568 None => Err("Invalid month".to_string())
570 'C' => match match_digits_in_range(s, pos, 2u, false, 0_i32,
574 tm.tm_year += (v * 100_i32) - 1900_i32;
577 None => Err("Invalid year".to_string())
580 parse_type(s, pos, 'a', &mut *tm)
581 .and_then(|pos| parse_char(s, pos, ' '))
582 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
583 .and_then(|pos| parse_char(s, pos, ' '))
584 .and_then(|pos| parse_type(s, pos, 'e', &mut *tm))
585 .and_then(|pos| parse_char(s, pos, ' '))
586 .and_then(|pos| parse_type(s, pos, 'T', &mut *tm))
587 .and_then(|pos| parse_char(s, pos, ' '))
588 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
591 parse_type(s, pos, 'm', &mut *tm)
592 .and_then(|pos| parse_char(s, pos, '/'))
593 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
594 .and_then(|pos| parse_char(s, pos, '/'))
595 .and_then(|pos| parse_type(s, pos, 'y', &mut *tm))
597 'd' => match match_digits_in_range(s, pos, 2u, false, 1_i32,
599 Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
600 None => Err("Invalid day of the month".to_string())
602 'e' => match match_digits_in_range(s, pos, 2u, true, 1_i32,
604 Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
605 None => Err("Invalid day of the month".to_string())
608 let (val, pos) = match_fractional_seconds(s, pos);
613 parse_type(s, pos, 'Y', &mut *tm)
614 .and_then(|pos| parse_char(s, pos, '-'))
615 .and_then(|pos| parse_type(s, pos, 'm', &mut *tm))
616 .and_then(|pos| parse_char(s, pos, '-'))
617 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
620 match match_digits_in_range(s, pos, 2u, false, 0_i32, 23_i32) {
621 Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
622 None => Err("Invalid hour".to_string())
626 match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
629 tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
632 None => Err("Invalid hour".to_string())
636 match match_digits_in_range(s, pos, 3u, false, 1_i32, 366_i32) {
639 tm.tm_yday = v - 1_i32;
642 None => Err("Invalid day of year".to_string())
646 match match_digits_in_range(s, pos, 2u, true, 0_i32, 23_i32) {
647 Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
648 None => Err("Invalid hour".to_string())
652 match match_digits_in_range(s, pos, 2u, true, 1_i32, 12_i32) {
655 tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
658 None => Err("Invalid hour".to_string())
662 match match_digits_in_range(s, pos, 2u, false, 0_i32, 59_i32) {
663 Some(item) => { let (v, pos) = item; tm.tm_min = v; Ok(pos) }
664 None => Err("Invalid minute".to_string())
668 match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
671 tm.tm_mon = v - 1_i32;
674 None => Err("Invalid month".to_string())
677 'n' => parse_char(s, pos, '\n'),
678 'P' => match match_strs(s, pos,
679 [("am", 0_i32), ("pm", 12_i32)]) {
681 Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
682 None => Err("Invalid hour".to_string())
684 'p' => match match_strs(s, pos,
685 [("AM", 0_i32), ("PM", 12_i32)]) {
687 Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
688 None => Err("Invalid hour".to_string())
691 parse_type(s, pos, 'H', &mut *tm)
692 .and_then(|pos| parse_char(s, pos, ':'))
693 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
696 parse_type(s, pos, 'I', &mut *tm)
697 .and_then(|pos| parse_char(s, pos, ':'))
698 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
699 .and_then(|pos| parse_char(s, pos, ':'))
700 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
701 .and_then(|pos| parse_char(s, pos, ' '))
702 .and_then(|pos| parse_type(s, pos, 'p', &mut *tm))
705 match match_digits_in_range(s, pos, 2u, false, 0_i32, 60_i32) {
711 None => Err("Invalid second".to_string())
716 parse_type(s, pos, 'H', &mut *tm)
717 .and_then(|pos| parse_char(s, pos, ':'))
718 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
719 .and_then(|pos| parse_char(s, pos, ':'))
720 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
722 't' => parse_char(s, pos, '\t'),
724 match match_digits_in_range(s, pos, 1u, false, 1_i32, 7_i32) {
727 tm.tm_wday = if v == 7 { 0 } else { v };
730 None => Err("Invalid day of week".to_string())
734 parse_type(s, pos, 'e', &mut *tm)
735 .and_then(|pos| parse_char(s, pos, '-'))
736 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
737 .and_then(|pos| parse_char(s, pos, '-'))
738 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
742 match match_digits_in_range(s, pos, 1u, false, 0_i32, 6_i32) {
743 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
744 None => Err("Invalid day of week".to_string())
748 match match_digits(s, pos, 4u, false) {
751 tm.tm_year = v - 1900_i32;
754 None => Err("Invalid year".to_string())
758 match match_digits_in_range(s, pos, 2u, false, 0_i32, 99_i32) {
764 None => Err("Invalid year".to_string())
768 if match_str(s, pos, "UTC") || match_str(s, pos, "GMT") {
769 tm.tm_gmtoff = 0_i32;
772 // It's odd, but to maintain compatibility with c's
773 // strptime we ignore the timezone.
777 let range = s.char_range_at(pos);
779 if range.ch == ' ' { break; }
786 let range = s.char_range_at(pos);
788 if range.ch == '+' || range.ch == '-' {
789 match match_digits(s, range.next, 4u, false) {
793 tm.tm_gmtoff = 0_i32;
798 None => Err("Invalid zone offset".to_string())
801 Err("Invalid zone offset".to_string())
804 '%' => parse_char(s, pos, '%'),
806 Err(format!("unknown formatting type: {}", ch))
811 let mut rdr = BufReader::new(format.as_bytes());
827 let mut result = Err("Invalid time".to_string());
830 let range = s.char_range_at(pos);
832 let next = range.next;
835 let c = match rdr.read(buf) {
836 Ok(..) => buf[0] as char,
841 let ch = match rdr.read(buf) {
842 Ok(..) => buf[0] as char,
845 match parse_type(s, pos, ch, &mut tm) {
846 Ok(next) => pos = next,
847 Err(e) => { result = Err(e); break; }
857 if pos == len && rdr.tell().unwrap() == format.len() as u64 {
867 tm_isdst: tm.tm_isdst,
868 tm_gmtoff: tm.tm_gmtoff,
874 /// Formats the time according to the format string.
875 pub fn strftime(format: &str, tm: &Tm) -> String {
876 fn days_in_year(year: int) -> i32 {
877 if (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) {
878 366 /* Days in a leap year */
880 365 /* Days in a non-leap year */
884 fn iso_week_days(yday: i32, wday: i32) -> int {
885 /* The number of days from the first day of the first ISO week of this
886 * year to the year day YDAY with week day WDAY.
887 * ISO weeks start on Monday. The first ISO week has the year's first
889 * YDAY may be as small as yday_minimum.
891 let yday: int = yday as int;
892 let wday: int = wday as int;
893 let iso_week_start_wday: int = 1; /* Monday */
894 let iso_week1_wday: int = 4; /* Thursday */
895 let yday_minimum: int = 366;
896 /* Add enough to the first operand of % to make it nonnegative. */
897 let big_enough_multiple_of_7: int = (yday_minimum / 7 + 2) * 7;
899 yday - (yday - wday + iso_week1_wday + big_enough_multiple_of_7) % 7
900 + iso_week1_wday - iso_week_start_wday
903 fn iso_week(ch:char, tm: &Tm) -> String {
904 let mut year: int = tm.tm_year as int + 1900;
905 let mut days: int = iso_week_days (tm.tm_yday, tm.tm_wday);
908 /* This ISO week belongs to the previous year. */
910 days = iso_week_days (tm.tm_yday + (days_in_year(year)), tm.tm_wday);
912 let d: int = iso_week_days (tm.tm_yday - (days_in_year(year)),
915 /* This ISO week belongs to the next year. */
922 'G' => format!("{}", year),
923 'g' => format!("{:02d}", (year % 100 + 100) % 100),
924 'V' => format!("{:02d}", days / 7 + 1),
929 fn parse_type(ch: char, tm: &Tm) -> String {
931 format!("strftime: can't understand this format {} ", ch)
934 'A' => match tm.tm_wday as int {
935 0 => "Sunday".to_string(),
936 1 => "Monday".to_string(),
937 2 => "Tuesday".to_string(),
938 3 => "Wednesday".to_string(),
939 4 => "Thursday".to_string(),
940 5 => "Friday".to_string(),
941 6 => "Saturday".to_string(),
944 'a' => match tm.tm_wday as int {
945 0 => "Sun".to_string(),
946 1 => "Mon".to_string(),
947 2 => "Tue".to_string(),
948 3 => "Wed".to_string(),
949 4 => "Thu".to_string(),
950 5 => "Fri".to_string(),
951 6 => "Sat".to_string(),
954 'B' => match tm.tm_mon as int {
955 0 => "January".to_string(),
956 1 => "February".to_string(),
957 2 => "March".to_string(),
958 3 => "April".to_string(),
959 4 => "May".to_string(),
960 5 => "June".to_string(),
961 6 => "July".to_string(),
962 7 => "August".to_string(),
963 8 => "September".to_string(),
964 9 => "October".to_string(),
965 10 => "November".to_string(),
966 11 => "December".to_string(),
969 'b' | 'h' => match tm.tm_mon as int {
970 0 => "Jan".to_string(),
971 1 => "Feb".to_string(),
972 2 => "Mar".to_string(),
973 3 => "Apr".to_string(),
974 4 => "May".to_string(),
975 5 => "Jun".to_string(),
976 6 => "Jul".to_string(),
977 7 => "Aug".to_string(),
978 8 => "Sep".to_string(),
979 9 => "Oct".to_string(),
980 10 => "Nov".to_string(),
981 11 => "Dec".to_string(),
984 'C' => format!("{:02d}", (tm.tm_year as int + 1900) / 100),
986 format!("{} {} {} {} {}",
999 'd' => format!("{:02d}", tm.tm_mday),
1000 'e' => format!("{:2d}", tm.tm_mday),
1001 'f' => format!("{:09d}", tm.tm_nsec),
1004 parse_type('Y', tm),
1005 parse_type('m', tm),
1006 parse_type('d', tm))
1008 'G' => iso_week('G', tm),
1009 'g' => iso_week('g', tm),
1010 'H' => format!("{:02d}", tm.tm_hour),
1012 let mut h = tm.tm_hour;
1013 if h == 0 { h = 12 }
1014 if h > 12 { h -= 12 }
1015 format!("{:02d}", h)
1017 'j' => format!("{:03d}", tm.tm_yday + 1),
1018 'k' => format!("{:2d}", tm.tm_hour),
1020 let mut h = tm.tm_hour;
1021 if h == 0 { h = 12 }
1022 if h > 12 { h -= 12 }
1025 'M' => format!("{:02d}", tm.tm_min),
1026 'm' => format!("{:02d}", tm.tm_mon + 1),
1027 'n' => "\n".to_string(),
1028 'P' => if (tm.tm_hour as int) < 12 { "am".to_string() } else { "pm".to_string() },
1029 'p' => if (tm.tm_hour as int) < 12 { "AM".to_string() } else { "PM".to_string() },
1032 parse_type('H', tm),
1033 parse_type('M', tm))
1036 format!("{}:{}:{} {}",
1037 parse_type('I', tm),
1038 parse_type('M', tm),
1039 parse_type('S', tm),
1040 parse_type('p', tm))
1042 'S' => format!("{:02d}", tm.tm_sec),
1043 's' => format!("{}", tm.to_timespec().sec),
1046 parse_type('H', tm),
1047 parse_type('M', tm),
1048 parse_type('S', tm))
1050 't' => "\t".to_string(),
1051 'U' => format!("{:02d}", (tm.tm_yday - tm.tm_wday + 7) / 7),
1053 let i = tm.tm_wday as int;
1054 (if i == 0 { 7 } else { i }).to_string()
1056 'V' => iso_week('V', tm),
1059 parse_type('e', tm),
1060 parse_type('b', tm),
1061 parse_type('Y', tm))
1065 (tm.tm_yday - (tm.tm_wday - 1 + 7) % 7 + 7) / 7)
1067 'w' => (tm.tm_wday as int).to_string(),
1068 'Y' => (tm.tm_year as int + 1900).to_string(),
1069 'y' => format!("{:02d}", (tm.tm_year as int + 1900) % 100),
1071 let sign = if tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
1072 let mut m = num::abs(tm.tm_gmtoff) / 60_i32;
1075 format!("{}{:02d}{:02d}", sign, h, m)
1077 '+' => tm.rfc3339(),
1078 '%' => "%".to_string(),
1083 let mut buf = Vec::new();
1085 let mut rdr = BufReader::new(format.as_bytes());
1088 let ch = match rdr.read(b) {
1094 rdr.read(b).unwrap();
1095 let s = parse_type(b[0] as char, tm);
1096 buf.push_all(s.as_bytes());
1098 ch => buf.push(ch as u8)
1102 String::from_utf8(buf).unwrap()
1108 use super::{Timespec, get_time, precise_time_ns, precise_time_s, tzset,
1109 at_utc, at, strptime};
1112 use std::result::{Err, Ok};
1113 use std::time::Duration;
1114 use self::test::Bencher;
1117 fn set_time_zone() {
1119 // Windows crt doesn't see any environment variable set by
1120 // `SetEnvironmentVariable`, which `os::setenv` internally uses.
1121 // It is why we use `putenv` here.
1123 fn _putenv(envstring: *const libc::c_char) -> libc::c_int;
1127 // Windows does not understand "America/Los_Angeles".
1128 // PST+08 may look wrong, but not! "PST" indicates
1129 // the name of timezone. "+08" means UTC = local + 08.
1130 "TZ=PST+08".with_c_str(|env| {
1136 #[cfg(not(windows))]
1137 fn set_time_zone() {
1139 os::setenv("TZ", "America/Los_Angeles");
1143 fn test_get_time() {
1144 static SOME_RECENT_DATE: i64 = 1325376000i64; // 2012-01-01T00:00:00Z
1145 static SOME_FUTURE_DATE: i64 = 1577836800i64; // 2020-01-01T00:00:00Z
1147 let tv1 = get_time();
1148 debug!("tv1={:?} sec + {:?} nsec", tv1.sec as uint, tv1.nsec as uint);
1150 assert!(tv1.sec > SOME_RECENT_DATE);
1151 assert!(tv1.nsec < 1000000000i32);
1153 let tv2 = get_time();
1154 debug!("tv2={:?} sec + {:?} nsec", tv2.sec as uint, tv2.nsec as uint);
1156 assert!(tv2.sec >= tv1.sec);
1157 assert!(tv2.sec < SOME_FUTURE_DATE);
1158 assert!(tv2.nsec < 1000000000i32);
1159 if tv2.sec == tv1.sec {
1160 assert!(tv2.nsec >= tv1.nsec);
1164 fn test_precise_time() {
1165 let s0 = precise_time_s();
1166 debug!("s0={} sec", f64::to_str_digits(s0, 9u));
1169 let ns0 = precise_time_ns();
1170 let ns1 = precise_time_ns();
1171 debug!("ns0={:?} ns", ns0);
1172 debug!("ns1={:?} ns", ns1);
1173 assert!(ns1 >= ns0);
1175 let ns2 = precise_time_ns();
1176 debug!("ns2={:?} ns", ns2);
1177 assert!(ns2 >= ns1);
1183 let time = Timespec::new(1234567890, 54321);
1184 let utc = at_utc(time);
1186 assert_eq!(utc.tm_sec, 30_i32);
1187 assert_eq!(utc.tm_min, 31_i32);
1188 assert_eq!(utc.tm_hour, 23_i32);
1189 assert_eq!(utc.tm_mday, 13_i32);
1190 assert_eq!(utc.tm_mon, 1_i32);
1191 assert_eq!(utc.tm_year, 109_i32);
1192 assert_eq!(utc.tm_wday, 5_i32);
1193 assert_eq!(utc.tm_yday, 43_i32);
1194 assert_eq!(utc.tm_isdst, 0_i32);
1195 assert_eq!(utc.tm_gmtoff, 0_i32);
1196 assert_eq!(utc.tm_nsec, 54321_i32);
1202 let time = Timespec::new(1234567890, 54321);
1203 let local = at(time);
1205 debug!("time_at: {:?}", local);
1207 assert_eq!(local.tm_sec, 30_i32);
1208 assert_eq!(local.tm_min, 31_i32);
1209 assert_eq!(local.tm_hour, 15_i32);
1210 assert_eq!(local.tm_mday, 13_i32);
1211 assert_eq!(local.tm_mon, 1_i32);
1212 assert_eq!(local.tm_year, 109_i32);
1213 assert_eq!(local.tm_wday, 5_i32);
1214 assert_eq!(local.tm_yday, 43_i32);
1215 assert_eq!(local.tm_isdst, 0_i32);
1216 assert_eq!(local.tm_gmtoff, -28800_i32);
1217 assert_eq!(local.tm_nsec, 54321_i32);
1220 fn test_to_timespec() {
1223 let time = Timespec::new(1234567890, 54321);
1224 let utc = at_utc(time);
1226 assert_eq!(utc.to_timespec(), time);
1227 assert_eq!(utc.to_local().to_timespec(), time);
1230 fn test_conversions() {
1233 let time = Timespec::new(1234567890, 54321);
1234 let utc = at_utc(time);
1235 let local = at(time);
1237 assert!(local.to_local() == local);
1238 assert!(local.to_utc() == utc);
1239 assert!(local.to_utc().to_local() == local);
1240 assert!(utc.to_utc() == utc);
1241 assert!(utc.to_local() == local);
1242 assert!(utc.to_local().to_utc() == utc);
1245 fn test_strptime() {
1248 match strptime("", "") {
1250 assert!(tm.tm_sec == 0_i32);
1251 assert!(tm.tm_min == 0_i32);
1252 assert!(tm.tm_hour == 0_i32);
1253 assert!(tm.tm_mday == 0_i32);
1254 assert!(tm.tm_mon == 0_i32);
1255 assert!(tm.tm_year == 0_i32);
1256 assert!(tm.tm_wday == 0_i32);
1257 assert!(tm.tm_isdst == 0_i32);
1258 assert!(tm.tm_gmtoff == 0_i32);
1259 assert!(tm.tm_nsec == 0_i32);
1264 let format = "%a %b %e %T.%f %Y";
1265 assert_eq!(strptime("", format), Err("Invalid time".to_string()));
1266 assert!(strptime("Fri Feb 13 15:31:30", format)
1267 == Err("Invalid time".to_string()));
1269 match strptime("Fri Feb 13 15:31:30.01234 2009", format) {
1272 assert!(tm.tm_sec == 30_i32);
1273 assert!(tm.tm_min == 31_i32);
1274 assert!(tm.tm_hour == 15_i32);
1275 assert!(tm.tm_mday == 13_i32);
1276 assert!(tm.tm_mon == 1_i32);
1277 assert!(tm.tm_year == 109_i32);
1278 assert!(tm.tm_wday == 5_i32);
1279 assert!(tm.tm_yday == 0_i32);
1280 assert!(tm.tm_isdst == 0_i32);
1281 assert!(tm.tm_gmtoff == 0_i32);
1282 assert!(tm.tm_nsec == 12340000_i32);
1286 fn test(s: &str, format: &str) -> bool {
1287 match strptime(s, format) {
1288 Ok(ref tm) => tm.strftime(format) == s.to_string(),
1294 "Sunday".to_string(),
1295 "Monday".to_string(),
1296 "Tuesday".to_string(),
1297 "Wednesday".to_string(),
1298 "Thursday".to_string(),
1299 "Friday".to_string(),
1300 "Saturday".to_string()
1302 for day in days.iter() {
1303 assert!(test(day.as_slice(), "%A"));
1315 for day in days.iter() {
1316 assert!(test(day.as_slice(), "%a"));
1320 "January".to_string(),
1321 "February".to_string(),
1322 "March".to_string(),
1323 "April".to_string(),
1327 "August".to_string(),
1328 "September".to_string(),
1329 "October".to_string(),
1330 "November".to_string(),
1331 "December".to_string()
1333 for day in months.iter() {
1334 assert!(test(day.as_slice(), "%B"));
1351 for day in months.iter() {
1352 assert!(test(day.as_slice(), "%b"));
1355 assert!(test("19", "%C"));
1356 assert!(test("Fri Feb 13 23:31:30 2009", "%c"));
1357 assert!(test("02/13/09", "%D"));
1358 assert!(test("03", "%d"));
1359 assert!(test("13", "%d"));
1360 assert!(test(" 3", "%e"));
1361 assert!(test("13", "%e"));
1362 assert!(test("2009-02-13", "%F"));
1363 assert!(test("03", "%H"));
1364 assert!(test("13", "%H"));
1365 assert!(test("03", "%I")); // FIXME (#2350): flesh out
1366 assert!(test("11", "%I")); // FIXME (#2350): flesh out
1367 assert!(test("044", "%j"));
1368 assert!(test(" 3", "%k"));
1369 assert!(test("13", "%k"));
1370 assert!(test(" 1", "%l"));
1371 assert!(test("11", "%l"));
1372 assert!(test("03", "%M"));
1373 assert!(test("13", "%M"));
1374 assert!(test("\n", "%n"));
1375 assert!(test("am", "%P"));
1376 assert!(test("pm", "%P"));
1377 assert!(test("AM", "%p"));
1378 assert!(test("PM", "%p"));
1379 assert!(test("23:31", "%R"));
1380 assert!(test("11:31:30 AM", "%r"));
1381 assert!(test("11:31:30 PM", "%r"));
1382 assert!(test("03", "%S"));
1383 assert!(test("13", "%S"));
1384 assert!(test("15:31:30", "%T"));
1385 assert!(test("\t", "%t"));
1386 assert!(test("1", "%u"));
1387 assert!(test("7", "%u"));
1388 assert!(test("13-Feb-2009", "%v"));
1389 assert!(test("0", "%w"));
1390 assert!(test("6", "%w"));
1391 assert!(test("2009", "%Y"));
1392 assert!(test("09", "%y"));
1393 assert!(strptime("-0000", "%z").unwrap().tm_gmtoff ==
1395 assert!(strptime("-0800", "%z").unwrap().tm_gmtoff ==
1397 assert!(test("%", "%%"));
1400 assert_eq!(strptime("360", "%Y-%m-%d"), Err("Invalid year".to_string()))
1406 let time = Timespec::new(1234567890, 54321);
1407 let utc = at_utc(time);
1408 let local = at(time);
1410 debug!("test_ctime: {:?} {:?}", utc.asctime(), local.asctime());
1412 assert_eq!(utc.asctime(), "Fri Feb 13 23:31:30 2009".to_string());
1413 assert_eq!(local.asctime(), "Fri Feb 13 15:31:30 2009".to_string());
1419 let time = Timespec::new(1234567890, 54321);
1420 let utc = at_utc(time);
1421 let local = at(time);
1423 debug!("test_ctime: {:?} {:?}", utc.ctime(), local.ctime());
1425 assert_eq!(utc.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1426 assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1429 fn test_strftime() {
1432 let time = Timespec::new(1234567890, 54321);
1433 let utc = at_utc(time);
1434 let local = at(time);
1436 assert_eq!(local.strftime(""), "".to_string());
1437 assert_eq!(local.strftime("%A"), "Friday".to_string());
1438 assert_eq!(local.strftime("%a"), "Fri".to_string());
1439 assert_eq!(local.strftime("%B"), "February".to_string());
1440 assert_eq!(local.strftime("%b"), "Feb".to_string());
1441 assert_eq!(local.strftime("%C"), "20".to_string());
1442 assert_eq!(local.strftime("%c"), "Fri Feb 13 15:31:30 2009".to_string());
1443 assert_eq!(local.strftime("%D"), "02/13/09".to_string());
1444 assert_eq!(local.strftime("%d"), "13".to_string());
1445 assert_eq!(local.strftime("%e"), "13".to_string());
1446 assert_eq!(local.strftime("%f"), "000054321".to_string());
1447 assert_eq!(local.strftime("%F"), "2009-02-13".to_string());
1448 assert_eq!(local.strftime("%G"), "2009".to_string());
1449 assert_eq!(local.strftime("%g"), "09".to_string());
1450 assert_eq!(local.strftime("%H"), "15".to_string());
1451 assert_eq!(local.strftime("%I"), "03".to_string());
1452 assert_eq!(local.strftime("%j"), "044".to_string());
1453 assert_eq!(local.strftime("%k"), "15".to_string());
1454 assert_eq!(local.strftime("%l"), " 3".to_string());
1455 assert_eq!(local.strftime("%M"), "31".to_string());
1456 assert_eq!(local.strftime("%m"), "02".to_string());
1457 assert_eq!(local.strftime("%n"), "\n".to_string());
1458 assert_eq!(local.strftime("%P"), "pm".to_string());
1459 assert_eq!(local.strftime("%p"), "PM".to_string());
1460 assert_eq!(local.strftime("%R"), "15:31".to_string());
1461 assert_eq!(local.strftime("%r"), "03:31:30 PM".to_string());
1462 assert_eq!(local.strftime("%S"), "30".to_string());
1463 assert_eq!(local.strftime("%s"), "1234567890".to_string());
1464 assert_eq!(local.strftime("%T"), "15:31:30".to_string());
1465 assert_eq!(local.strftime("%t"), "\t".to_string());
1466 assert_eq!(local.strftime("%U"), "06".to_string());
1467 assert_eq!(local.strftime("%u"), "5".to_string());
1468 assert_eq!(local.strftime("%V"), "07".to_string());
1469 assert_eq!(local.strftime("%v"), "13-Feb-2009".to_string());
1470 assert_eq!(local.strftime("%W"), "06".to_string());
1471 assert_eq!(local.strftime("%w"), "5".to_string());
1472 assert_eq!(local.strftime("%X"), "15:31:30".to_string()); // FIXME (#2350): support locale
1473 assert_eq!(local.strftime("%x"), "02/13/09".to_string()); // FIXME (#2350): support locale
1474 assert_eq!(local.strftime("%Y"), "2009".to_string());
1475 assert_eq!(local.strftime("%y"), "09".to_string());
1476 assert_eq!(local.strftime("%+"), "2009-02-13T15:31:30-08:00".to_string());
1477 assert_eq!(local.strftime("%z"), "-0800".to_string());
1478 assert_eq!(local.strftime("%%"), "%".to_string());
1480 assert_eq!(local.asctime(), "Fri Feb 13 15:31:30 2009".to_string());
1481 assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1482 assert_eq!(local.rfc822z(), "Fri, 13 Feb 2009 15:31:30 -0800".to_string());
1483 assert_eq!(local.rfc3339(), "2009-02-13T15:31:30-08:00".to_string());
1485 assert_eq!(utc.asctime(), "Fri Feb 13 23:31:30 2009".to_string());
1486 assert_eq!(utc.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1487 assert_eq!(utc.rfc822(), "Fri, 13 Feb 2009 23:31:30 GMT".to_string());
1488 assert_eq!(utc.rfc822z(), "Fri, 13 Feb 2009 23:31:30 -0000".to_string());
1489 assert_eq!(utc.rfc3339(), "2009-02-13T23:31:30Z".to_string());
1492 fn test_timespec_eq_ord() {
1493 let a = &Timespec::new(-2, 1);
1494 let b = &Timespec::new(-1, 2);
1495 let c = &Timespec::new(1, 2);
1496 let d = &Timespec::new(2, 1);
1497 let e = &Timespec::new(2, 1);
1523 fn test_timespec_add() {
1524 let a = Timespec::new(1, 2);
1525 let b = Duration::seconds(2) + Duration::nanoseconds(3);
1527 assert_eq!(c.sec, 3);
1528 assert_eq!(c.nsec, 5);
1530 let p = Timespec::new(1, super::NSEC_PER_SEC - 2);
1531 let q = Duration::seconds(2) + Duration::nanoseconds(2);
1533 assert_eq!(r.sec, 4);
1534 assert_eq!(r.nsec, 0);
1536 let u = Timespec::new(1, super::NSEC_PER_SEC - 2);
1537 let v = Duration::seconds(2) + Duration::nanoseconds(3);
1539 assert_eq!(w.sec, 4);
1540 assert_eq!(w.nsec, 1);
1542 let k = Timespec::new(1, 0);
1543 let l = Duration::nanoseconds(-1);
1545 assert_eq!(m.sec, 0);
1546 assert_eq!(m.nsec, 999_999_999);
1549 fn test_timespec_sub() {
1550 let a = Timespec::new(2, 3);
1551 let b = Timespec::new(1, 2);
1553 assert_eq!(c.num_nanoseconds(), Some(super::NSEC_PER_SEC as i64 + 1));
1555 let p = Timespec::new(2, 0);
1556 let q = Timespec::new(1, 2);
1558 assert_eq!(r.num_nanoseconds(), Some(super::NSEC_PER_SEC as i64 - 2));
1560 let u = Timespec::new(1, 2);
1561 let v = Timespec::new(2, 3);
1563 assert_eq!(w.num_nanoseconds(), Some(-super::NSEC_PER_SEC as i64 - 1));
1567 #[cfg_attr(target_os = "android", ignore)] // FIXME #10958
1569 // The tests race on tzset. So instead of having many independent
1570 // tests, we will just call the functions now.
1572 test_precise_time();
1581 test_timespec_eq_ord();
1582 test_timespec_add();
1583 test_timespec_sub();
1587 fn bench_precise_time_ns(b: &mut Bencher) {
1588 b.iter(|| precise_time_ns())