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(all(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(any(target_os = "macos", target_os = "ios"))]
66 use libc::{timeval, timezone, c_int, mach_timebase_info};
69 pub fn gettimeofday(tp: *mut timeval, tzp: *mut timezone) -> c_int;
70 pub fn mach_absolute_time() -> u64;
71 pub fn mach_timebase_info(info: *mut mach_timebase_info) -> c_int;
75 /// A record specifying a time value in seconds and nanoseconds.
76 #[deriving(Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Show)]
77 pub struct Timespec { pub sec: i64, pub nsec: i32 }
79 * Timespec assumes that pre-epoch Timespecs have negative sec and positive
80 * nsec fields. Darwin's and Linux's struct timespec functions handle pre-
81 * epoch timestamps using a "two steps back, one step forward" representation,
82 * though the man pages do not actually document this. For example, the time
83 * -1.2 seconds before the epoch is represented by `Timespec { sec: -2_i64,
84 * nsec: 800_000_000_i32 }`.
87 pub fn new(sec: i64, nsec: i32) -> Timespec {
88 assert!(nsec >= 0 && nsec < NSEC_PER_SEC);
89 Timespec { sec: sec, nsec: nsec }
93 impl Add<Duration, Timespec> for Timespec {
94 fn add(&self, other: &Duration) -> Timespec {
95 let d_sec = other.num_seconds();
96 // It is safe to unwrap the nanoseconds, because there cannot be
97 // more than one second left, which fits in i64 and in i32.
98 let d_nsec = (other - Duration::seconds(d_sec))
99 .num_nanoseconds().unwrap() as i32;
100 let mut sec = self.sec + d_sec;
101 let mut nsec = self.nsec + d_nsec;
102 if nsec >= NSEC_PER_SEC {
103 nsec -= NSEC_PER_SEC;
106 nsec += NSEC_PER_SEC;
109 Timespec::new(sec, nsec)
113 impl Sub<Timespec, Duration> for Timespec {
114 fn sub(&self, other: &Timespec) -> Duration {
115 let sec = self.sec - other.sec;
116 let nsec = self.nsec - other.nsec;
117 Duration::seconds(sec) + Duration::nanoseconds(nsec as i64)
122 * Returns the current time as a `timespec` containing the seconds and
123 * nanoseconds since 1970-01-01T00:00:00Z.
125 pub fn get_time() -> Timespec {
127 let (sec, nsec) = os_get_time();
128 return Timespec::new(sec, nsec);
132 unsafe fn os_get_time() -> (i64, i32) {
133 static NANOSECONDS_FROM_1601_TO_1970: u64 = 11644473600000000;
135 let mut time = libc::FILETIME {
139 libc::GetSystemTimeAsFileTime(&mut time);
141 // A FILETIME contains a 64-bit value representing the number of
142 // hectonanosecond (100-nanosecond) intervals since 1601-01-01T00:00:00Z.
143 // http://support.microsoft.com/kb/167296/en-us
144 let ns_since_1601 = ((time.dwHighDateTime as u64 << 32) |
145 (time.dwLowDateTime as u64 << 0)) / 10;
146 let ns_since_1970 = ns_since_1601 - NANOSECONDS_FROM_1601_TO_1970;
148 ((ns_since_1970 / 1000000) as i64,
149 ((ns_since_1970 % 1000000) * 1000) as i32)
152 #[cfg(any(target_os = "macos", target_os = "ios"))]
153 unsafe fn os_get_time() -> (i64, i32) {
155 let mut tv = libc::timeval { tv_sec: 0, tv_usec: 0 };
156 imp::gettimeofday(&mut tv, ptr::null_mut());
157 (tv.tv_sec as i64, tv.tv_usec * 1000)
160 #[cfg(not(any(target_os = "macos", target_os = "ios", windows)))]
161 unsafe fn os_get_time() -> (i64, i32) {
162 let mut tv = libc::timespec { tv_sec: 0, tv_nsec: 0 };
163 imp::clock_gettime(libc::CLOCK_REALTIME, &mut tv);
164 (tv.tv_sec as i64, tv.tv_nsec as i32)
170 * Returns the current value of a high-resolution performance counter
171 * in nanoseconds since an unspecified epoch.
173 pub fn precise_time_ns() -> u64 {
174 return os_precise_time_ns();
177 fn os_precise_time_ns() -> u64 {
178 let mut ticks_per_s = 0;
180 libc::QueryPerformanceFrequency(&mut ticks_per_s)
182 let ticks_per_s = if ticks_per_s == 0 {1} else {ticks_per_s};
185 libc::QueryPerformanceCounter(&mut ticks)
188 return (ticks as u64 * 1000000000) / (ticks_per_s as u64);
191 #[cfg(any(target_os = "macos", target_os = "ios"))]
192 fn os_precise_time_ns() -> u64 {
193 static mut TIMEBASE: libc::mach_timebase_info = libc::mach_timebase_info { numer: 0,
195 static mut ONCE: std::sync::Once = std::sync::ONCE_INIT;
198 imp::mach_timebase_info(&mut TIMEBASE);
200 let time = imp::mach_absolute_time();
201 time * TIMEBASE.numer as u64 / TIMEBASE.denom as u64
205 #[cfg(not(any(windows, target_os = "macos", target_os = "ios")))]
206 fn os_precise_time_ns() -> u64 {
207 let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
209 imp::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts);
211 return (ts.tv_sec as u64) * 1000000000 + (ts.tv_nsec as u64)
217 * Returns the current value of a high-resolution performance counter
218 * in seconds since an unspecified epoch.
220 pub fn precise_time_s() -> f64 {
221 return (precise_time_ns() as f64) / 1000000000.;
226 rustrt::rust_tzset();
230 /// Holds a calendar date and time broken down into its components (year, month, day, and so on),
231 /// also called a broken-down time value.
232 // FIXME: use c_int instead of i32?
234 #[deriving(Clone, PartialEq, Eq, Show)]
236 /// Seconds after the minute - [0, 60]
239 /// Minutes after the hour - [0, 59]
242 /// Hours after midnight - [0, 23]
245 /// Day of the month - [1, 31]
248 /// Months since January - [0, 11]
254 /// Days since Sunday - [0, 6]. 0 = Sunday, 1 = Monday, ..., 6 = Saturday.
257 /// Days since January 1 - [0, 365]
260 /// Daylight Saving Time flag.
262 /// This value is positive if Daylight Saving Time is in effect, zero if Daylight Saving Time
263 /// is not in effect, and negative if this information is not available.
266 /// Identifies the time zone that was used to compute this broken-down time value, including any
267 /// adjustment for Daylight Saving Time. This is the number of seconds east of UTC. For example,
268 /// for U.S. Pacific Daylight Time, the value is -7*60*60 = -25200.
271 /// Nanoseconds after the second - [0, 10<sup>9</sup> - 1]
275 pub fn empty_tm() -> Tm {
291 /// Returns the specified time in UTC
292 pub fn at_utc(clock: Timespec) -> Tm {
294 let Timespec { sec, nsec } = clock;
295 let mut tm = empty_tm();
296 rustrt::rust_gmtime(sec, nsec, &mut tm);
301 /// Returns the current time in UTC
302 pub fn now_utc() -> Tm {
306 /// Returns the specified time in the local timezone
307 pub fn at(clock: Timespec) -> Tm {
309 let Timespec { sec, nsec } = clock;
310 let mut tm = empty_tm();
311 rustrt::rust_localtime(sec, nsec, &mut tm);
316 /// Returns the current time in the local timezone
323 /// Convert time to the seconds from January 1, 1970
324 pub fn to_timespec(&self) -> Timespec {
326 let sec = match self.tm_gmtoff {
327 0_i32 => rustrt::rust_timegm(self),
328 _ => rustrt::rust_mktime(self)
331 Timespec::new(sec, self.tm_nsec)
335 /// Convert time to the local timezone
336 pub fn to_local(&self) -> Tm {
337 at(self.to_timespec())
340 /// Convert time to the UTC
341 pub fn to_utc(&self) -> Tm {
342 at_utc(self.to_timespec())
346 * Returns a time string formatted according to the `asctime` format in ISO
347 * C, in the local timezone.
349 * Example: "Thu Jan 1 00:00:00 1970"
351 pub fn ctime(&self) -> String {
352 self.to_local().asctime()
356 * Returns a time string formatted according to the `asctime` format in ISO
359 * Example: "Thu Jan 1 00:00:00 1970"
361 pub fn asctime(&self) -> String {
365 /// Formats the time according to the format string.
366 pub fn strftime(&self, format: &str) -> String {
367 strftime(format, self)
371 * Returns a time string formatted according to RFC 822.
373 * local: "Thu, 22 Mar 2012 07:53:18 PST"
374 * utc: "Thu, 22 Mar 2012 14:53:18 GMT"
376 pub fn rfc822(&self) -> String {
377 if self.tm_gmtoff == 0_i32 {
378 self.strftime("%a, %d %b %Y %T GMT")
380 self.strftime("%a, %d %b %Y %T %Z")
385 * Returns a time string formatted according to RFC 822 with Zulu time.
387 * local: "Thu, 22 Mar 2012 07:53:18 -0700"
388 * utc: "Thu, 22 Mar 2012 14:53:18 -0000"
390 pub fn rfc822z(&self) -> String {
391 self.strftime("%a, %d %b %Y %T %z")
395 * Returns a time string formatted according to RFC 3339. RFC 3339 is
396 * compatible with ISO 8601.
398 * local: "2012-02-22T07:53:18-07:00"
399 * utc: "2012-02-22T14:53:18Z"
401 pub fn rfc3339(&self) -> String {
402 if self.tm_gmtoff == 0_i32 {
403 self.strftime("%Y-%m-%dT%H:%M:%SZ")
405 let s = self.strftime("%Y-%m-%dT%H:%M:%S");
406 let sign = if self.tm_gmtoff > 0_i32 { '+' } else { '-' };
407 let mut m = num::abs(self.tm_gmtoff) / 60_i32;
410 format!("{}{}{:02d}:{:02d}", s, sign, h as int, m as int)
415 /// Parses the time from the string according to the format string.
416 pub fn strptime(s: &str, format: &str) -> Result<Tm, String> {
417 fn match_str(s: &str, pos: uint, needle: &str) -> bool {
418 return s.slice_from(pos).starts_with(needle);
421 fn match_strs(ss: &str, pos: uint, strs: &[(&str, i32)])
422 -> Option<(i32, uint)> {
423 for &(needle, value) in strs.iter() {
424 if match_str(ss, pos, needle) {
425 return Some((value, pos + needle.len()));
432 fn match_digits(ss: &str, pos: uint, digits: uint, ws: bool)
433 -> Option<(i32, uint)> {
436 let mut value = 0_i32;
443 let range = ss.char_range_at(pos);
448 value = value * 10_i32 + (range.ch as i32 - '0' as i32);
459 fn match_fractional_seconds(ss: &str, pos: uint) -> (i32, uint) {
461 let mut value = 0_i32;
462 let mut multiplier = NSEC_PER_SEC / 10;
469 let range = ss.char_range_at(pos);
474 // This will drop digits after the nanoseconds place
475 let digit = range.ch as i32 - '0' as i32;
476 value += digit * multiplier;
486 fn match_digits_in_range(ss: &str, pos: uint, digits: uint, ws: bool,
487 min: i32, max: i32) -> Option<(i32, uint)> {
488 match match_digits(ss, pos, digits, ws) {
489 Some((val, pos)) if val >= min && val <= max => {
496 fn parse_char(s: &str, pos: uint, c: char) -> Result<uint, String> {
497 let range = s.char_range_at(pos);
502 Err(format!("Expected {}, found {}", c, range.ch))
506 fn parse_type(s: &str, pos: uint, ch: char, tm: &mut Tm)
507 -> Result<uint, String> {
509 'A' => match match_strs(s, pos, [
513 ("Wednesday", 3_i32),
518 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
519 None => Err("Invalid day".to_string())
521 'a' => match match_strs(s, pos, [
530 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
531 None => Err("Invalid day".to_string())
533 'B' => match match_strs(s, pos, [
542 ("September", 8_i32),
544 ("November", 10_i32),
547 Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
548 None => Err("Invalid month".to_string())
550 'b' | 'h' => match match_strs(s, pos, [
564 Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
565 None => Err("Invalid month".to_string())
567 'C' => match match_digits_in_range(s, pos, 2u, false, 0_i32,
571 tm.tm_year += (v * 100_i32) - 1900_i32;
574 None => Err("Invalid year".to_string())
577 parse_type(s, pos, 'a', &mut *tm)
578 .and_then(|pos| parse_char(s, pos, ' '))
579 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
580 .and_then(|pos| parse_char(s, pos, ' '))
581 .and_then(|pos| parse_type(s, pos, 'e', &mut *tm))
582 .and_then(|pos| parse_char(s, pos, ' '))
583 .and_then(|pos| parse_type(s, pos, 'T', &mut *tm))
584 .and_then(|pos| parse_char(s, pos, ' '))
585 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
588 parse_type(s, pos, 'm', &mut *tm)
589 .and_then(|pos| parse_char(s, pos, '/'))
590 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
591 .and_then(|pos| parse_char(s, pos, '/'))
592 .and_then(|pos| parse_type(s, pos, 'y', &mut *tm))
594 'd' => match match_digits_in_range(s, pos, 2u, false, 1_i32,
596 Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
597 None => Err("Invalid day of the month".to_string())
599 'e' => match match_digits_in_range(s, pos, 2u, true, 1_i32,
601 Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
602 None => Err("Invalid day of the month".to_string())
605 let (val, pos) = match_fractional_seconds(s, pos);
610 parse_type(s, pos, 'Y', &mut *tm)
611 .and_then(|pos| parse_char(s, pos, '-'))
612 .and_then(|pos| parse_type(s, pos, 'm', &mut *tm))
613 .and_then(|pos| parse_char(s, pos, '-'))
614 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
617 match match_digits_in_range(s, pos, 2u, false, 0_i32, 23_i32) {
618 Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
619 None => Err("Invalid hour".to_string())
623 match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
626 tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
629 None => Err("Invalid hour".to_string())
633 match match_digits_in_range(s, pos, 3u, false, 1_i32, 366_i32) {
636 tm.tm_yday = v - 1_i32;
639 None => Err("Invalid day of year".to_string())
643 match match_digits_in_range(s, pos, 2u, true, 0_i32, 23_i32) {
644 Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
645 None => Err("Invalid hour".to_string())
649 match match_digits_in_range(s, pos, 2u, true, 1_i32, 12_i32) {
652 tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
655 None => Err("Invalid hour".to_string())
659 match match_digits_in_range(s, pos, 2u, false, 0_i32, 59_i32) {
660 Some(item) => { let (v, pos) = item; tm.tm_min = v; Ok(pos) }
661 None => Err("Invalid minute".to_string())
665 match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
668 tm.tm_mon = v - 1_i32;
671 None => Err("Invalid month".to_string())
674 'n' => parse_char(s, pos, '\n'),
675 'P' => match match_strs(s, pos,
676 [("am", 0_i32), ("pm", 12_i32)]) {
678 Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
679 None => Err("Invalid hour".to_string())
681 'p' => match match_strs(s, pos,
682 [("AM", 0_i32), ("PM", 12_i32)]) {
684 Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
685 None => Err("Invalid hour".to_string())
688 parse_type(s, pos, 'H', &mut *tm)
689 .and_then(|pos| parse_char(s, pos, ':'))
690 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
693 parse_type(s, pos, 'I', &mut *tm)
694 .and_then(|pos| parse_char(s, pos, ':'))
695 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
696 .and_then(|pos| parse_char(s, pos, ':'))
697 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
698 .and_then(|pos| parse_char(s, pos, ' '))
699 .and_then(|pos| parse_type(s, pos, 'p', &mut *tm))
702 match match_digits_in_range(s, pos, 2u, false, 0_i32, 60_i32) {
708 None => Err("Invalid second".to_string())
713 parse_type(s, pos, 'H', &mut *tm)
714 .and_then(|pos| parse_char(s, pos, ':'))
715 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
716 .and_then(|pos| parse_char(s, pos, ':'))
717 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
719 't' => parse_char(s, pos, '\t'),
721 match match_digits_in_range(s, pos, 1u, false, 1_i32, 7_i32) {
724 tm.tm_wday = if v == 7 { 0 } else { v };
727 None => Err("Invalid day of week".to_string())
731 parse_type(s, pos, 'e', &mut *tm)
732 .and_then(|pos| parse_char(s, pos, '-'))
733 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
734 .and_then(|pos| parse_char(s, pos, '-'))
735 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
739 match match_digits_in_range(s, pos, 1u, false, 0_i32, 6_i32) {
740 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
741 None => Err("Invalid day of week".to_string())
745 match match_digits(s, pos, 4u, false) {
748 tm.tm_year = v - 1900_i32;
751 None => Err("Invalid year".to_string())
755 match match_digits_in_range(s, pos, 2u, false, 0_i32, 99_i32) {
761 None => Err("Invalid year".to_string())
765 if match_str(s, pos, "UTC") || match_str(s, pos, "GMT") {
766 tm.tm_gmtoff = 0_i32;
769 // It's odd, but to maintain compatibility with c's
770 // strptime we ignore the timezone.
774 let range = s.char_range_at(pos);
776 if range.ch == ' ' { break; }
783 let range = s.char_range_at(pos);
785 if range.ch == '+' || range.ch == '-' {
786 match match_digits(s, range.next, 4u, false) {
790 tm.tm_gmtoff = 0_i32;
795 None => Err("Invalid zone offset".to_string())
798 Err("Invalid zone offset".to_string())
801 '%' => parse_char(s, pos, '%'),
803 Err(format!("unknown formatting type: {}", ch))
808 let mut rdr = BufReader::new(format.as_bytes());
824 let mut result = Err("Invalid time".to_string());
827 let range = s.char_range_at(pos);
829 let next = range.next;
832 let c = match rdr.read(buf) {
833 Ok(..) => buf[0] as char,
838 let ch = match rdr.read(buf) {
839 Ok(..) => buf[0] as char,
842 match parse_type(s, pos, ch, &mut tm) {
843 Ok(next) => pos = next,
844 Err(e) => { result = Err(e); break; }
854 if pos == len && rdr.tell().unwrap() == format.len() as u64 {
864 tm_isdst: tm.tm_isdst,
865 tm_gmtoff: tm.tm_gmtoff,
871 /// Formats the time according to the format string.
872 pub fn strftime(format: &str, tm: &Tm) -> String {
873 fn days_in_year(year: int) -> i32 {
874 if (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) {
875 366 /* Days in a leap year */
877 365 /* Days in a non-leap year */
881 fn iso_week_days(yday: i32, wday: i32) -> int {
882 /* The number of days from the first day of the first ISO week of this
883 * year to the year day YDAY with week day WDAY.
884 * ISO weeks start on Monday. The first ISO week has the year's first
886 * YDAY may be as small as yday_minimum.
888 let yday: int = yday as int;
889 let wday: int = wday as int;
890 let iso_week_start_wday: int = 1; /* Monday */
891 let iso_week1_wday: int = 4; /* Thursday */
892 let yday_minimum: int = 366;
893 /* Add enough to the first operand of % to make it nonnegative. */
894 let big_enough_multiple_of_7: int = (yday_minimum / 7 + 2) * 7;
896 yday - (yday - wday + iso_week1_wday + big_enough_multiple_of_7) % 7
897 + iso_week1_wday - iso_week_start_wday
900 fn iso_week(ch:char, tm: &Tm) -> String {
901 let mut year: int = tm.tm_year as int + 1900;
902 let mut days: int = iso_week_days (tm.tm_yday, tm.tm_wday);
905 /* This ISO week belongs to the previous year. */
907 days = iso_week_days (tm.tm_yday + (days_in_year(year)), tm.tm_wday);
909 let d: int = iso_week_days (tm.tm_yday - (days_in_year(year)),
912 /* This ISO week belongs to the next year. */
919 'G' => format!("{}", year),
920 'g' => format!("{:02d}", (year % 100 + 100) % 100),
921 'V' => format!("{:02d}", days / 7 + 1),
926 fn parse_type(ch: char, tm: &Tm) -> String {
928 format!("strftime: can't understand this format {} ", ch)
931 'A' => match tm.tm_wday as int {
932 0 => "Sunday".to_string(),
933 1 => "Monday".to_string(),
934 2 => "Tuesday".to_string(),
935 3 => "Wednesday".to_string(),
936 4 => "Thursday".to_string(),
937 5 => "Friday".to_string(),
938 6 => "Saturday".to_string(),
941 'a' => match tm.tm_wday as int {
942 0 => "Sun".to_string(),
943 1 => "Mon".to_string(),
944 2 => "Tue".to_string(),
945 3 => "Wed".to_string(),
946 4 => "Thu".to_string(),
947 5 => "Fri".to_string(),
948 6 => "Sat".to_string(),
951 'B' => match tm.tm_mon as int {
952 0 => "January".to_string(),
953 1 => "February".to_string(),
954 2 => "March".to_string(),
955 3 => "April".to_string(),
956 4 => "May".to_string(),
957 5 => "June".to_string(),
958 6 => "July".to_string(),
959 7 => "August".to_string(),
960 8 => "September".to_string(),
961 9 => "October".to_string(),
962 10 => "November".to_string(),
963 11 => "December".to_string(),
966 'b' | 'h' => match tm.tm_mon as int {
967 0 => "Jan".to_string(),
968 1 => "Feb".to_string(),
969 2 => "Mar".to_string(),
970 3 => "Apr".to_string(),
971 4 => "May".to_string(),
972 5 => "Jun".to_string(),
973 6 => "Jul".to_string(),
974 7 => "Aug".to_string(),
975 8 => "Sep".to_string(),
976 9 => "Oct".to_string(),
977 10 => "Nov".to_string(),
978 11 => "Dec".to_string(),
981 'C' => format!("{:02d}", (tm.tm_year as int + 1900) / 100),
983 format!("{} {} {} {} {}",
996 'd' => format!("{:02d}", tm.tm_mday),
997 'e' => format!("{:2d}", tm.tm_mday),
998 'f' => format!("{:09d}", tm.tm_nsec),
1001 parse_type('Y', tm),
1002 parse_type('m', tm),
1003 parse_type('d', tm))
1005 'G' => iso_week('G', tm),
1006 'g' => iso_week('g', tm),
1007 'H' => format!("{:02d}", tm.tm_hour),
1009 let mut h = tm.tm_hour;
1010 if h == 0 { h = 12 }
1011 if h > 12 { h -= 12 }
1012 format!("{:02d}", h)
1014 'j' => format!("{:03d}", tm.tm_yday + 1),
1015 'k' => format!("{:2d}", tm.tm_hour),
1017 let mut h = tm.tm_hour;
1018 if h == 0 { h = 12 }
1019 if h > 12 { h -= 12 }
1022 'M' => format!("{:02d}", tm.tm_min),
1023 'm' => format!("{:02d}", tm.tm_mon + 1),
1024 'n' => "\n".to_string(),
1025 'P' => if (tm.tm_hour as int) < 12 { "am".to_string() } else { "pm".to_string() },
1026 'p' => if (tm.tm_hour as int) < 12 { "AM".to_string() } else { "PM".to_string() },
1029 parse_type('H', tm),
1030 parse_type('M', tm))
1033 format!("{}:{}:{} {}",
1034 parse_type('I', tm),
1035 parse_type('M', tm),
1036 parse_type('S', tm),
1037 parse_type('p', tm))
1039 'S' => format!("{:02d}", tm.tm_sec),
1040 's' => format!("{}", tm.to_timespec().sec),
1043 parse_type('H', tm),
1044 parse_type('M', tm),
1045 parse_type('S', tm))
1047 't' => "\t".to_string(),
1048 'U' => format!("{:02d}", (tm.tm_yday - tm.tm_wday + 7) / 7),
1050 let i = tm.tm_wday as int;
1051 (if i == 0 { 7 } else { i }).to_string()
1053 'V' => iso_week('V', tm),
1056 parse_type('e', tm),
1057 parse_type('b', tm),
1058 parse_type('Y', tm))
1062 (tm.tm_yday - (tm.tm_wday - 1 + 7) % 7 + 7) / 7)
1064 'w' => (tm.tm_wday as int).to_string(),
1065 'Y' => (tm.tm_year as int + 1900).to_string(),
1066 'y' => format!("{:02d}", (tm.tm_year as int + 1900) % 100),
1068 let sign = if tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
1069 let mut m = num::abs(tm.tm_gmtoff) / 60_i32;
1072 format!("{}{:02d}{:02d}", sign, h, m)
1074 '+' => tm.rfc3339(),
1075 '%' => "%".to_string(),
1080 let mut buf = Vec::new();
1082 let mut rdr = BufReader::new(format.as_bytes());
1085 let ch = match rdr.read(b) {
1091 rdr.read(b).unwrap();
1092 let s = parse_type(b[0] as char, tm);
1093 buf.push_all(s.as_bytes());
1095 ch => buf.push(ch as u8)
1099 String::from_utf8(buf).unwrap()
1105 use super::{Timespec, get_time, precise_time_ns, precise_time_s, tzset,
1106 at_utc, at, strptime};
1109 use std::result::{Err, Ok};
1110 use std::time::Duration;
1111 use self::test::Bencher;
1114 fn set_time_zone() {
1116 // Windows crt doesn't see any environment variable set by
1117 // `SetEnvironmentVariable`, which `os::setenv` internally uses.
1118 // It is why we use `putenv` here.
1120 fn _putenv(envstring: *const libc::c_char) -> libc::c_int;
1124 // Windows does not understand "America/Los_Angeles".
1125 // PST+08 may look wrong, but not! "PST" indicates
1126 // the name of timezone. "+08" means UTC = local + 08.
1127 "TZ=PST+08".with_c_str(|env| {
1133 #[cfg(not(windows))]
1134 fn set_time_zone() {
1136 os::setenv("TZ", "America/Los_Angeles");
1140 fn test_get_time() {
1141 static SOME_RECENT_DATE: i64 = 1325376000i64; // 2012-01-01T00:00:00Z
1142 static SOME_FUTURE_DATE: i64 = 1577836800i64; // 2020-01-01T00:00:00Z
1144 let tv1 = get_time();
1145 debug!("tv1={:?} sec + {:?} nsec", tv1.sec as uint, tv1.nsec as uint);
1147 assert!(tv1.sec > SOME_RECENT_DATE);
1148 assert!(tv1.nsec < 1000000000i32);
1150 let tv2 = get_time();
1151 debug!("tv2={:?} sec + {:?} nsec", tv2.sec as uint, tv2.nsec as uint);
1153 assert!(tv2.sec >= tv1.sec);
1154 assert!(tv2.sec < SOME_FUTURE_DATE);
1155 assert!(tv2.nsec < 1000000000i32);
1156 if tv2.sec == tv1.sec {
1157 assert!(tv2.nsec >= tv1.nsec);
1161 fn test_precise_time() {
1162 let s0 = precise_time_s();
1163 debug!("s0={} sec", f64::to_str_digits(s0, 9u));
1166 let ns0 = precise_time_ns();
1167 let ns1 = precise_time_ns();
1168 debug!("ns0={:?} ns", ns0);
1169 debug!("ns1={:?} ns", ns1);
1170 assert!(ns1 >= ns0);
1172 let ns2 = precise_time_ns();
1173 debug!("ns2={:?} ns", ns2);
1174 assert!(ns2 >= ns1);
1180 let time = Timespec::new(1234567890, 54321);
1181 let utc = at_utc(time);
1183 assert_eq!(utc.tm_sec, 30_i32);
1184 assert_eq!(utc.tm_min, 31_i32);
1185 assert_eq!(utc.tm_hour, 23_i32);
1186 assert_eq!(utc.tm_mday, 13_i32);
1187 assert_eq!(utc.tm_mon, 1_i32);
1188 assert_eq!(utc.tm_year, 109_i32);
1189 assert_eq!(utc.tm_wday, 5_i32);
1190 assert_eq!(utc.tm_yday, 43_i32);
1191 assert_eq!(utc.tm_isdst, 0_i32);
1192 assert_eq!(utc.tm_gmtoff, 0_i32);
1193 assert_eq!(utc.tm_nsec, 54321_i32);
1199 let time = Timespec::new(1234567890, 54321);
1200 let local = at(time);
1202 debug!("time_at: {:?}", local);
1204 assert_eq!(local.tm_sec, 30_i32);
1205 assert_eq!(local.tm_min, 31_i32);
1206 assert_eq!(local.tm_hour, 15_i32);
1207 assert_eq!(local.tm_mday, 13_i32);
1208 assert_eq!(local.tm_mon, 1_i32);
1209 assert_eq!(local.tm_year, 109_i32);
1210 assert_eq!(local.tm_wday, 5_i32);
1211 assert_eq!(local.tm_yday, 43_i32);
1212 assert_eq!(local.tm_isdst, 0_i32);
1213 assert_eq!(local.tm_gmtoff, -28800_i32);
1214 assert_eq!(local.tm_nsec, 54321_i32);
1217 fn test_to_timespec() {
1220 let time = Timespec::new(1234567890, 54321);
1221 let utc = at_utc(time);
1223 assert_eq!(utc.to_timespec(), time);
1224 assert_eq!(utc.to_local().to_timespec(), time);
1227 fn test_conversions() {
1230 let time = Timespec::new(1234567890, 54321);
1231 let utc = at_utc(time);
1232 let local = at(time);
1234 assert!(local.to_local() == local);
1235 assert!(local.to_utc() == utc);
1236 assert!(local.to_utc().to_local() == local);
1237 assert!(utc.to_utc() == utc);
1238 assert!(utc.to_local() == local);
1239 assert!(utc.to_local().to_utc() == utc);
1242 fn test_strptime() {
1245 match strptime("", "") {
1247 assert!(tm.tm_sec == 0_i32);
1248 assert!(tm.tm_min == 0_i32);
1249 assert!(tm.tm_hour == 0_i32);
1250 assert!(tm.tm_mday == 0_i32);
1251 assert!(tm.tm_mon == 0_i32);
1252 assert!(tm.tm_year == 0_i32);
1253 assert!(tm.tm_wday == 0_i32);
1254 assert!(tm.tm_isdst == 0_i32);
1255 assert!(tm.tm_gmtoff == 0_i32);
1256 assert!(tm.tm_nsec == 0_i32);
1261 let format = "%a %b %e %T.%f %Y";
1262 assert_eq!(strptime("", format), Err("Invalid time".to_string()));
1263 assert!(strptime("Fri Feb 13 15:31:30", format)
1264 == Err("Invalid time".to_string()));
1266 match strptime("Fri Feb 13 15:31:30.01234 2009", format) {
1269 assert!(tm.tm_sec == 30_i32);
1270 assert!(tm.tm_min == 31_i32);
1271 assert!(tm.tm_hour == 15_i32);
1272 assert!(tm.tm_mday == 13_i32);
1273 assert!(tm.tm_mon == 1_i32);
1274 assert!(tm.tm_year == 109_i32);
1275 assert!(tm.tm_wday == 5_i32);
1276 assert!(tm.tm_yday == 0_i32);
1277 assert!(tm.tm_isdst == 0_i32);
1278 assert!(tm.tm_gmtoff == 0_i32);
1279 assert!(tm.tm_nsec == 12340000_i32);
1283 fn test(s: &str, format: &str) -> bool {
1284 match strptime(s, format) {
1285 Ok(ref tm) => tm.strftime(format) == s.to_string(),
1291 "Sunday".to_string(),
1292 "Monday".to_string(),
1293 "Tuesday".to_string(),
1294 "Wednesday".to_string(),
1295 "Thursday".to_string(),
1296 "Friday".to_string(),
1297 "Saturday".to_string()
1299 for day in days.iter() {
1300 assert!(test(day.as_slice(), "%A"));
1312 for day in days.iter() {
1313 assert!(test(day.as_slice(), "%a"));
1317 "January".to_string(),
1318 "February".to_string(),
1319 "March".to_string(),
1320 "April".to_string(),
1324 "August".to_string(),
1325 "September".to_string(),
1326 "October".to_string(),
1327 "November".to_string(),
1328 "December".to_string()
1330 for day in months.iter() {
1331 assert!(test(day.as_slice(), "%B"));
1348 for day in months.iter() {
1349 assert!(test(day.as_slice(), "%b"));
1352 assert!(test("19", "%C"));
1353 assert!(test("Fri Feb 13 23:31:30 2009", "%c"));
1354 assert!(test("02/13/09", "%D"));
1355 assert!(test("03", "%d"));
1356 assert!(test("13", "%d"));
1357 assert!(test(" 3", "%e"));
1358 assert!(test("13", "%e"));
1359 assert!(test("2009-02-13", "%F"));
1360 assert!(test("03", "%H"));
1361 assert!(test("13", "%H"));
1362 assert!(test("03", "%I")); // FIXME (#2350): flesh out
1363 assert!(test("11", "%I")); // FIXME (#2350): flesh out
1364 assert!(test("044", "%j"));
1365 assert!(test(" 3", "%k"));
1366 assert!(test("13", "%k"));
1367 assert!(test(" 1", "%l"));
1368 assert!(test("11", "%l"));
1369 assert!(test("03", "%M"));
1370 assert!(test("13", "%M"));
1371 assert!(test("\n", "%n"));
1372 assert!(test("am", "%P"));
1373 assert!(test("pm", "%P"));
1374 assert!(test("AM", "%p"));
1375 assert!(test("PM", "%p"));
1376 assert!(test("23:31", "%R"));
1377 assert!(test("11:31:30 AM", "%r"));
1378 assert!(test("11:31:30 PM", "%r"));
1379 assert!(test("03", "%S"));
1380 assert!(test("13", "%S"));
1381 assert!(test("15:31:30", "%T"));
1382 assert!(test("\t", "%t"));
1383 assert!(test("1", "%u"));
1384 assert!(test("7", "%u"));
1385 assert!(test("13-Feb-2009", "%v"));
1386 assert!(test("0", "%w"));
1387 assert!(test("6", "%w"));
1388 assert!(test("2009", "%Y"));
1389 assert!(test("09", "%y"));
1390 assert!(strptime("-0000", "%z").unwrap().tm_gmtoff ==
1392 assert!(strptime("-0800", "%z").unwrap().tm_gmtoff ==
1394 assert!(test("%", "%%"));
1397 assert_eq!(strptime("360", "%Y-%m-%d"), Err("Invalid year".to_string()))
1403 let time = Timespec::new(1234567890, 54321);
1404 let utc = at_utc(time);
1405 let local = at(time);
1407 debug!("test_ctime: {:?} {:?}", utc.asctime(), local.asctime());
1409 assert_eq!(utc.asctime(), "Fri Feb 13 23:31:30 2009".to_string());
1410 assert_eq!(local.asctime(), "Fri Feb 13 15:31:30 2009".to_string());
1416 let time = Timespec::new(1234567890, 54321);
1417 let utc = at_utc(time);
1418 let local = at(time);
1420 debug!("test_ctime: {:?} {:?}", utc.ctime(), local.ctime());
1422 assert_eq!(utc.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1423 assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1426 fn test_strftime() {
1429 let time = Timespec::new(1234567890, 54321);
1430 let utc = at_utc(time);
1431 let local = at(time);
1433 assert_eq!(local.strftime(""), "".to_string());
1434 assert_eq!(local.strftime("%A"), "Friday".to_string());
1435 assert_eq!(local.strftime("%a"), "Fri".to_string());
1436 assert_eq!(local.strftime("%B"), "February".to_string());
1437 assert_eq!(local.strftime("%b"), "Feb".to_string());
1438 assert_eq!(local.strftime("%C"), "20".to_string());
1439 assert_eq!(local.strftime("%c"), "Fri Feb 13 15:31:30 2009".to_string());
1440 assert_eq!(local.strftime("%D"), "02/13/09".to_string());
1441 assert_eq!(local.strftime("%d"), "13".to_string());
1442 assert_eq!(local.strftime("%e"), "13".to_string());
1443 assert_eq!(local.strftime("%f"), "000054321".to_string());
1444 assert_eq!(local.strftime("%F"), "2009-02-13".to_string());
1445 assert_eq!(local.strftime("%G"), "2009".to_string());
1446 assert_eq!(local.strftime("%g"), "09".to_string());
1447 assert_eq!(local.strftime("%H"), "15".to_string());
1448 assert_eq!(local.strftime("%I"), "03".to_string());
1449 assert_eq!(local.strftime("%j"), "044".to_string());
1450 assert_eq!(local.strftime("%k"), "15".to_string());
1451 assert_eq!(local.strftime("%l"), " 3".to_string());
1452 assert_eq!(local.strftime("%M"), "31".to_string());
1453 assert_eq!(local.strftime("%m"), "02".to_string());
1454 assert_eq!(local.strftime("%n"), "\n".to_string());
1455 assert_eq!(local.strftime("%P"), "pm".to_string());
1456 assert_eq!(local.strftime("%p"), "PM".to_string());
1457 assert_eq!(local.strftime("%R"), "15:31".to_string());
1458 assert_eq!(local.strftime("%r"), "03:31:30 PM".to_string());
1459 assert_eq!(local.strftime("%S"), "30".to_string());
1460 assert_eq!(local.strftime("%s"), "1234567890".to_string());
1461 assert_eq!(local.strftime("%T"), "15:31:30".to_string());
1462 assert_eq!(local.strftime("%t"), "\t".to_string());
1463 assert_eq!(local.strftime("%U"), "06".to_string());
1464 assert_eq!(local.strftime("%u"), "5".to_string());
1465 assert_eq!(local.strftime("%V"), "07".to_string());
1466 assert_eq!(local.strftime("%v"), "13-Feb-2009".to_string());
1467 assert_eq!(local.strftime("%W"), "06".to_string());
1468 assert_eq!(local.strftime("%w"), "5".to_string());
1469 assert_eq!(local.strftime("%X"), "15:31:30".to_string()); // FIXME (#2350): support locale
1470 assert_eq!(local.strftime("%x"), "02/13/09".to_string()); // FIXME (#2350): support locale
1471 assert_eq!(local.strftime("%Y"), "2009".to_string());
1472 assert_eq!(local.strftime("%y"), "09".to_string());
1473 assert_eq!(local.strftime("%+"), "2009-02-13T15:31:30-08:00".to_string());
1474 assert_eq!(local.strftime("%z"), "-0800".to_string());
1475 assert_eq!(local.strftime("%%"), "%".to_string());
1477 assert_eq!(local.asctime(), "Fri Feb 13 15:31:30 2009".to_string());
1478 assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1479 assert_eq!(local.rfc822z(), "Fri, 13 Feb 2009 15:31:30 -0800".to_string());
1480 assert_eq!(local.rfc3339(), "2009-02-13T15:31:30-08:00".to_string());
1482 assert_eq!(utc.asctime(), "Fri Feb 13 23:31:30 2009".to_string());
1483 assert_eq!(utc.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1484 assert_eq!(utc.rfc822(), "Fri, 13 Feb 2009 23:31:30 GMT".to_string());
1485 assert_eq!(utc.rfc822z(), "Fri, 13 Feb 2009 23:31:30 -0000".to_string());
1486 assert_eq!(utc.rfc3339(), "2009-02-13T23:31:30Z".to_string());
1489 fn test_timespec_eq_ord() {
1490 let a = &Timespec::new(-2, 1);
1491 let b = &Timespec::new(-1, 2);
1492 let c = &Timespec::new(1, 2);
1493 let d = &Timespec::new(2, 1);
1494 let e = &Timespec::new(2, 1);
1520 fn test_timespec_add() {
1521 let a = Timespec::new(1, 2);
1522 let b = Duration::seconds(2) + Duration::nanoseconds(3);
1524 assert_eq!(c.sec, 3);
1525 assert_eq!(c.nsec, 5);
1527 let p = Timespec::new(1, super::NSEC_PER_SEC - 2);
1528 let q = Duration::seconds(2) + Duration::nanoseconds(2);
1530 assert_eq!(r.sec, 4);
1531 assert_eq!(r.nsec, 0);
1533 let u = Timespec::new(1, super::NSEC_PER_SEC - 2);
1534 let v = Duration::seconds(2) + Duration::nanoseconds(3);
1536 assert_eq!(w.sec, 4);
1537 assert_eq!(w.nsec, 1);
1539 let k = Timespec::new(1, 0);
1540 let l = Duration::nanoseconds(-1);
1542 assert_eq!(m.sec, 0);
1543 assert_eq!(m.nsec, 999_999_999);
1546 fn test_timespec_sub() {
1547 let a = Timespec::new(2, 3);
1548 let b = Timespec::new(1, 2);
1550 assert_eq!(c.num_nanoseconds(), Some(super::NSEC_PER_SEC as i64 + 1));
1552 let p = Timespec::new(2, 0);
1553 let q = Timespec::new(1, 2);
1555 assert_eq!(r.num_nanoseconds(), Some(super::NSEC_PER_SEC as i64 - 2));
1557 let u = Timespec::new(1, 2);
1558 let v = Timespec::new(2, 3);
1560 assert_eq!(w.num_nanoseconds(), Some(-super::NSEC_PER_SEC as i64 - 1));
1564 #[cfg_attr(target_os = "android", ignore)] // FIXME #10958
1566 // The tests race on tzset. So instead of having many independent
1567 // tests, we will just call the functions now.
1569 test_precise_time();
1578 test_timespec_eq_ord();
1579 test_timespec_add();
1580 test_timespec_sub();
1584 fn bench_precise_time_ns(b: &mut Bencher) {
1585 b.iter(|| precise_time_ns())