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_id = "time#0.11.0-pre"]
15 #![crate_type = "rlib"]
16 #![crate_type = "dylib"]
17 #![license = "MIT/ASL2"]
18 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
19 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
20 html_root_url = "http://doc.rust-lang.org/")]
22 #![deny(deprecated_owned_vector)]
24 #[cfg(test)] extern crate debug;
25 #[cfg(test)] #[phase(syntax, link)] extern crate log;
27 extern crate serialize;
29 #[cfg(target_os = "macos")]
32 use std::io::BufReader;
34 use std::string::String;
37 static NSEC_PER_SEC: i32 = 1_000_000_000_i32;
44 pub fn rust_gmtime(sec: i64, nsec: i32, result: &mut Tm);
45 pub fn rust_localtime(sec: i64, nsec: i32, result: &mut Tm);
46 pub fn rust_timegm(tm: &Tm) -> i64;
47 pub fn rust_mktime(tm: &Tm) -> i64;
51 #[cfg(unix, not(target_os = "macos"))]
53 use libc::{c_int, timespec};
55 // Apparently android provides this in some other library?
56 #[cfg(not(target_os = "android"))]
61 pub fn clock_gettime(clk_id: c_int, tp: *mut timespec) -> c_int;
65 #[cfg(target_os = "macos")]
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, Eq, TotalEq, Ord, TotalOrd, 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 }
95 * Returns the current time as a `timespec` containing the seconds and
96 * nanoseconds since 1970-01-01T00:00:00Z.
98 pub fn get_time() -> Timespec {
100 let (sec, nsec) = os_get_time();
101 return Timespec::new(sec, nsec);
105 unsafe fn os_get_time() -> (i64, i32) {
106 static NANOSECONDS_FROM_1601_TO_1970: u64 = 11644473600000000;
108 let mut time = libc::FILETIME {
112 libc::GetSystemTimeAsFileTime(&mut time);
114 // A FILETIME contains a 64-bit value representing the number of
115 // hectonanosecond (100-nanosecond) intervals since 1601-01-01T00:00:00Z.
116 // http://support.microsoft.com/kb/167296/en-us
117 let ns_since_1601 = ((time.dwHighDateTime as u64 << 32) |
118 (time.dwLowDateTime as u64 << 0)) / 10;
119 let ns_since_1970 = ns_since_1601 - NANOSECONDS_FROM_1601_TO_1970;
121 ((ns_since_1970 / 1000000) as i64,
122 ((ns_since_1970 % 1000000) * 1000) as i32)
125 #[cfg(target_os = "macos")]
126 unsafe fn os_get_time() -> (i64, i32) {
128 let mut tv = libc::timeval { tv_sec: 0, tv_usec: 0 };
129 imp::gettimeofday(&mut tv, ptr::mut_null());
130 (tv.tv_sec as i64, tv.tv_usec * 1000)
133 #[cfg(not(target_os = "macos"), not(windows))]
134 unsafe fn os_get_time() -> (i64, i32) {
135 let mut tv = libc::timespec { tv_sec: 0, tv_nsec: 0 };
136 imp::clock_gettime(libc::CLOCK_REALTIME, &mut tv);
137 (tv.tv_sec as i64, tv.tv_nsec as i32)
143 * Returns the current value of a high-resolution performance counter
144 * in nanoseconds since an unspecified epoch.
146 pub fn precise_time_ns() -> u64 {
147 return os_precise_time_ns();
150 fn os_precise_time_ns() -> u64 {
151 let mut ticks_per_s = 0;
153 libc::QueryPerformanceFrequency(&mut ticks_per_s)
155 let ticks_per_s = if ticks_per_s == 0 {1} else {ticks_per_s};
158 libc::QueryPerformanceCounter(&mut ticks)
161 return (ticks as u64 * 1000000000) / (ticks_per_s as u64);
164 #[cfg(target_os = "macos")]
165 fn os_precise_time_ns() -> u64 {
166 static mut TIMEBASE: libc::mach_timebase_info = libc::mach_timebase_info { numer: 0,
168 static mut ONCE: sync::one::Once = sync::one::ONCE_INIT;
171 imp::mach_timebase_info(&mut TIMEBASE);
173 let time = imp::mach_absolute_time();
174 time * TIMEBASE.numer as u64 / TIMEBASE.denom as u64
178 #[cfg(not(windows), not(target_os = "macos"))]
179 fn os_precise_time_ns() -> u64 {
180 let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
182 imp::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts);
184 return (ts.tv_sec as u64) * 1000000000 + (ts.tv_nsec as u64)
190 * Returns the current value of a high-resolution performance counter
191 * in seconds since an unspecified epoch.
193 pub fn precise_time_s() -> f64 {
194 return (precise_time_ns() as f64) / 1000000000.;
199 rustrt::rust_tzset();
203 /// Holds a calendar date and time broken down into its components (year, month, day, and so on),
204 /// also called a broken-down time value.
205 #[deriving(Clone, Eq, Show)]
207 /// Seconds after the minute – [0, 60]
210 /// Minutes after the hour – [0, 59]
213 /// Hours after midnight – [0, 23]
216 /// Day of the month – [1, 31]
219 /// Months since January – [0, 11]
225 /// Days since Sunday – [0, 6]. 0 = Sunday, 1 = Monday, …, 6 = Saturday.
228 /// Days since January 1 – [0, 365]
231 /// Daylight Saving Time flag.
233 /// This value is positive if Daylight Saving Time is in effect, zero if Daylight Saving Time
234 /// is not in effect, and negative if this information is not available.
237 /// Identifies the time zone that was used to compute this broken-down time value, including any
238 /// adjustment for Daylight Saving Time. This is the number of seconds east of UTC. For example,
239 /// for U.S. Pacific Daylight Time, the value is -7*60*60 = -25200.
242 /// Nanoseconds after the second – [0, 10<sup>9</sup> - 1]
246 pub fn empty_tm() -> Tm {
262 /// Returns the specified time in UTC
263 pub fn at_utc(clock: Timespec) -> Tm {
265 let Timespec { sec, nsec } = clock;
266 let mut tm = empty_tm();
267 rustrt::rust_gmtime(sec, nsec, &mut tm);
272 /// Returns the current time in UTC
273 pub fn now_utc() -> Tm {
277 /// Returns the specified time in the local timezone
278 pub fn at(clock: Timespec) -> Tm {
280 let Timespec { sec, nsec } = clock;
281 let mut tm = empty_tm();
282 rustrt::rust_localtime(sec, nsec, &mut tm);
287 /// Returns the current time in the local timezone
294 /// Convert time to the seconds from January 1, 1970
295 pub fn to_timespec(&self) -> Timespec {
297 let sec = match self.tm_gmtoff {
298 0_i32 => rustrt::rust_timegm(self),
299 _ => rustrt::rust_mktime(self)
302 Timespec::new(sec, self.tm_nsec)
306 /// Convert time to the local timezone
307 pub fn to_local(&self) -> Tm {
308 at(self.to_timespec())
311 /// Convert time to the UTC
312 pub fn to_utc(&self) -> Tm {
313 at_utc(self.to_timespec())
317 * Return a string of the current time in the form
318 * "Thu Jan 1 00:00:00 1970".
320 pub fn ctime(&self) -> String { self.strftime("%c") }
322 /// Formats the time according to the format string.
323 pub fn strftime(&self, format: &str) -> String {
324 strftime(format, self)
328 * Returns a time string formatted according to RFC 822.
330 * local: "Thu, 22 Mar 2012 07:53:18 PST"
331 * utc: "Thu, 22 Mar 2012 14:53:18 UTC"
333 pub fn rfc822(&self) -> String {
334 if self.tm_gmtoff == 0_i32 {
335 self.strftime("%a, %d %b %Y %T GMT")
337 self.strftime("%a, %d %b %Y %T %Z")
342 * Returns a time string formatted according to RFC 822 with Zulu time.
344 * local: "Thu, 22 Mar 2012 07:53:18 -0700"
345 * utc: "Thu, 22 Mar 2012 14:53:18 -0000"
347 pub fn rfc822z(&self) -> String {
348 self.strftime("%a, %d %b %Y %T %z")
352 * Returns a time string formatted according to ISO 8601.
354 * local: "2012-02-22T07:53:18-07:00"
355 * utc: "2012-02-22T14:53:18Z"
357 pub fn rfc3339(&self) -> String {
358 if self.tm_gmtoff == 0_i32 {
359 self.strftime("%Y-%m-%dT%H:%M:%SZ")
361 let s = self.strftime("%Y-%m-%dT%H:%M:%S");
362 let sign = if self.tm_gmtoff > 0_i32 { '+' } else { '-' };
363 let mut m = num::abs(self.tm_gmtoff) / 60_i32;
366 format_strbuf!("{}{}{:02d}:{:02d}", s, sign, h as int, m as int)
371 /// Parses the time from the string according to the format string.
372 pub fn strptime(s: &str, format: &str) -> Result<Tm, String> {
373 fn match_str(s: &str, pos: uint, needle: &str) -> bool {
375 for ch in needle.bytes() {
384 fn match_strs(ss: &str, pos: uint, strs: &[(String, i32)])
385 -> Option<(i32, uint)> {
387 let len = strs.len();
389 match strs[i] { // can't use let due to let-pattern bugs
390 (ref needle, value) => {
391 if match_str(ss, pos, needle.as_slice()) {
392 return Some((value, pos + needle.len()));
402 fn match_digits(ss: &str, pos: uint, digits: uint, ws: bool)
403 -> Option<(i32, uint)> {
406 let mut value = 0_i32;
413 let range = ss.char_range_at(pos);
418 value = value * 10_i32 + (range.ch as i32 - '0' as i32);
429 fn match_fractional_seconds(ss: &str, pos: uint) -> (i32, uint) {
431 let mut value = 0_i32;
432 let mut multiplier = NSEC_PER_SEC / 10;
439 let range = ss.char_range_at(pos);
444 // This will drop digits after the nanoseconds place
445 let digit = range.ch as i32 - '0' as i32;
446 value += digit * multiplier;
456 fn match_digits_in_range(ss: &str, pos: uint, digits: uint, ws: bool,
457 min: i32, max: i32) -> Option<(i32, uint)> {
458 match match_digits(ss, pos, digits, ws) {
459 Some((val, pos)) if val >= min && val <= max => {
466 fn parse_char(s: &str, pos: uint, c: char) -> Result<uint, String> {
467 let range = s.char_range_at(pos);
472 Err(format_strbuf!("Expected {}, found {}",
474 str::from_char(range.ch)))
478 fn parse_type(s: &str, pos: uint, ch: char, tm: &mut Tm)
479 -> Result<uint, String> {
481 'A' => match match_strs(s, pos, [
482 ("Sunday".to_string(), 0_i32),
483 ("Monday".to_string(), 1_i32),
484 ("Tuesday".to_string(), 2_i32),
485 ("Wednesday".to_string(), 3_i32),
486 ("Thursday".to_string(), 4_i32),
487 ("Friday".to_string(), 5_i32),
488 ("Saturday".to_string(), 6_i32)
490 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
491 None => Err("Invalid day".to_string())
493 'a' => match match_strs(s, pos, [
494 ("Sun".to_string(), 0_i32),
495 ("Mon".to_string(), 1_i32),
496 ("Tue".to_string(), 2_i32),
497 ("Wed".to_string(), 3_i32),
498 ("Thu".to_string(), 4_i32),
499 ("Fri".to_string(), 5_i32),
500 ("Sat".to_string(), 6_i32)
502 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
503 None => Err("Invalid day".to_string())
505 'B' => match match_strs(s, pos, [
506 ("January".to_string(), 0_i32),
507 ("February".to_string(), 1_i32),
508 ("March".to_string(), 2_i32),
509 ("April".to_string(), 3_i32),
510 ("May".to_string(), 4_i32),
511 ("June".to_string(), 5_i32),
512 ("July".to_string(), 6_i32),
513 ("August".to_string(), 7_i32),
514 ("September".to_string(), 8_i32),
515 ("October".to_string(), 9_i32),
516 ("November".to_string(), 10_i32),
517 ("December".to_string(), 11_i32)
519 Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
520 None => Err("Invalid month".to_string())
522 'b' | 'h' => match match_strs(s, pos, [
523 ("Jan".to_string(), 0_i32),
524 ("Feb".to_string(), 1_i32),
525 ("Mar".to_string(), 2_i32),
526 ("Apr".to_string(), 3_i32),
527 ("May".to_string(), 4_i32),
528 ("Jun".to_string(), 5_i32),
529 ("Jul".to_string(), 6_i32),
530 ("Aug".to_string(), 7_i32),
531 ("Sep".to_string(), 8_i32),
532 ("Oct".to_string(), 9_i32),
533 ("Nov".to_string(), 10_i32),
534 ("Dec".to_string(), 11_i32)
536 Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
537 None => Err("Invalid month".to_string())
539 'C' => match match_digits_in_range(s, pos, 2u, false, 0_i32,
543 tm.tm_year += (v * 100_i32) - 1900_i32;
546 None => Err("Invalid year".to_string())
549 parse_type(s, pos, 'a', &mut *tm)
550 .and_then(|pos| parse_char(s, pos, ' '))
551 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
552 .and_then(|pos| parse_char(s, pos, ' '))
553 .and_then(|pos| parse_type(s, pos, 'e', &mut *tm))
554 .and_then(|pos| parse_char(s, pos, ' '))
555 .and_then(|pos| parse_type(s, pos, 'T', &mut *tm))
556 .and_then(|pos| parse_char(s, pos, ' '))
557 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
560 parse_type(s, pos, 'm', &mut *tm)
561 .and_then(|pos| parse_char(s, pos, '/'))
562 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
563 .and_then(|pos| parse_char(s, pos, '/'))
564 .and_then(|pos| parse_type(s, pos, 'y', &mut *tm))
566 'd' => match match_digits_in_range(s, pos, 2u, false, 1_i32,
568 Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
569 None => Err("Invalid day of the month".to_string())
571 'e' => match match_digits_in_range(s, pos, 2u, true, 1_i32,
573 Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
574 None => Err("Invalid day of the month".to_string())
577 let (val, pos) = match_fractional_seconds(s, pos);
582 parse_type(s, pos, 'Y', &mut *tm)
583 .and_then(|pos| parse_char(s, pos, '-'))
584 .and_then(|pos| parse_type(s, pos, 'm', &mut *tm))
585 .and_then(|pos| parse_char(s, pos, '-'))
586 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
589 match match_digits_in_range(s, pos, 2u, false, 0_i32, 23_i32) {
590 Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
591 None => Err("Invalid hour".to_string())
595 match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
598 tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
601 None => Err("Invalid hour".to_string())
605 match match_digits_in_range(s, pos, 3u, false, 1_i32, 366_i32) {
608 tm.tm_yday = v - 1_i32;
611 None => Err("Invalid day of year".to_string())
615 match match_digits_in_range(s, pos, 2u, true, 0_i32, 23_i32) {
616 Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
617 None => Err("Invalid hour".to_string())
621 match match_digits_in_range(s, pos, 2u, true, 1_i32, 12_i32) {
624 tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
627 None => Err("Invalid hour".to_string())
631 match match_digits_in_range(s, pos, 2u, false, 0_i32, 59_i32) {
632 Some(item) => { let (v, pos) = item; tm.tm_min = v; Ok(pos) }
633 None => Err("Invalid minute".to_string())
637 match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
640 tm.tm_mon = v - 1_i32;
643 None => Err("Invalid month".to_string())
646 'n' => parse_char(s, pos, '\n'),
647 'P' => match match_strs(s, pos,
648 [("am".to_string(), 0_i32), ("pm".to_string(), 12_i32)]) {
650 Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
651 None => Err("Invalid hour".to_string())
653 'p' => match match_strs(s, pos,
654 [("AM".to_string(), 0_i32), ("PM".to_string(), 12_i32)]) {
656 Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
657 None => Err("Invalid hour".to_string())
660 parse_type(s, pos, 'H', &mut *tm)
661 .and_then(|pos| parse_char(s, pos, ':'))
662 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
665 parse_type(s, pos, 'I', &mut *tm)
666 .and_then(|pos| parse_char(s, pos, ':'))
667 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
668 .and_then(|pos| parse_char(s, pos, ':'))
669 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
670 .and_then(|pos| parse_char(s, pos, ' '))
671 .and_then(|pos| parse_type(s, pos, 'p', &mut *tm))
674 match match_digits_in_range(s, pos, 2u, false, 0_i32, 60_i32) {
680 None => Err("Invalid second".to_string())
685 parse_type(s, pos, 'H', &mut *tm)
686 .and_then(|pos| parse_char(s, pos, ':'))
687 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
688 .and_then(|pos| parse_char(s, pos, ':'))
689 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
691 't' => parse_char(s, pos, '\t'),
693 match match_digits_in_range(s, pos, 1u, false, 1_i32, 7_i32) {
696 tm.tm_wday = if v == 7 { 0 } else { v };
699 None => Err("Invalid day of week".to_string())
703 parse_type(s, pos, 'e', &mut *tm)
704 .and_then(|pos| parse_char(s, pos, '-'))
705 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
706 .and_then(|pos| parse_char(s, pos, '-'))
707 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
711 match match_digits_in_range(s, pos, 1u, false, 0_i32, 6_i32) {
712 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
713 None => Err("Invalid day of week".to_string())
717 match match_digits(s, pos, 4u, false) {
720 tm.tm_year = v - 1900_i32;
723 None => Err("Invalid year".to_string())
727 match match_digits_in_range(s, pos, 2u, false, 0_i32, 99_i32) {
733 None => Err("Invalid year".to_string())
737 if match_str(s, pos, "UTC") || match_str(s, pos, "GMT") {
738 tm.tm_gmtoff = 0_i32;
741 // It's odd, but to maintain compatibility with c's
742 // strptime we ignore the timezone.
746 let range = s.char_range_at(pos);
748 if range.ch == ' ' { break; }
755 let range = s.char_range_at(pos);
757 if range.ch == '+' || range.ch == '-' {
758 match match_digits(s, range.next, 4u, false) {
762 tm.tm_gmtoff = 0_i32;
767 None => Err("Invalid zone offset".to_string())
770 Err("Invalid zone offset".to_string())
773 '%' => parse_char(s, pos, '%'),
775 Err(format_strbuf!("unknown formatting type: {}",
781 let mut rdr = BufReader::new(format.as_bytes());
797 let mut result = Err("Invalid time".to_string());
800 let range = s.char_range_at(pos);
802 let next = range.next;
805 let c = match rdr.read(buf) {
806 Ok(..) => buf[0] as char,
811 let ch = match rdr.read(buf) {
812 Ok(..) => buf[0] as char,
815 match parse_type(s, pos, ch, &mut tm) {
816 Ok(next) => pos = next,
817 Err(e) => { result = Err(e); break; }
827 if pos == len && rdr.tell().unwrap() == format.len() as u64 {
837 tm_isdst: tm.tm_isdst,
838 tm_gmtoff: tm.tm_gmtoff,
844 /// Formats the time according to the format string.
845 pub fn strftime(format: &str, tm: &Tm) -> String {
846 fn days_in_year(year: int) -> i32 {
847 if (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) {
848 366 /* Days in a leap year */
850 365 /* Days in a non-leap year */
854 fn iso_week_days(yday: i32, wday: i32) -> int {
855 /* The number of days from the first day of the first ISO week of this
856 * year to the year day YDAY with week day WDAY.
857 * ISO weeks start on Monday. The first ISO week has the year's first
859 * YDAY may be as small as yday_minimum.
861 let yday: int = yday as int;
862 let wday: int = wday as int;
863 let iso_week_start_wday: int = 1; /* Monday */
864 let iso_week1_wday: int = 4; /* Thursday */
865 let yday_minimum: int = 366;
866 /* Add enough to the first operand of % to make it nonnegative. */
867 let big_enough_multiple_of_7: int = (yday_minimum / 7 + 2) * 7;
869 yday - (yday - wday + iso_week1_wday + big_enough_multiple_of_7) % 7
870 + iso_week1_wday - iso_week_start_wday
873 fn iso_week(ch:char, tm: &Tm) -> String {
874 let mut year: int = tm.tm_year as int + 1900;
875 let mut days: int = iso_week_days (tm.tm_yday, tm.tm_wday);
878 /* This ISO week belongs to the previous year. */
880 days = iso_week_days (tm.tm_yday + (days_in_year(year)), tm.tm_wday);
882 let d: int = iso_week_days (tm.tm_yday - (days_in_year(year)),
885 /* This ISO week belongs to the next year. */
892 'G' => format_strbuf!("{}", year),
893 'g' => format_strbuf!("{:02d}", (year % 100 + 100) % 100),
894 'V' => format_strbuf!("{:02d}", days / 7 + 1),
899 fn parse_type(ch: char, tm: &Tm) -> String {
901 format_strbuf!("strftime: can't understand this format {} ", ch)
904 'A' => match tm.tm_wday as int {
905 0 => "Sunday".to_string(),
906 1 => "Monday".to_string(),
907 2 => "Tuesday".to_string(),
908 3 => "Wednesday".to_string(),
909 4 => "Thursday".to_string(),
910 5 => "Friday".to_string(),
911 6 => "Saturday".to_string(),
914 'a' => match tm.tm_wday as int {
915 0 => "Sun".to_string(),
916 1 => "Mon".to_string(),
917 2 => "Tue".to_string(),
918 3 => "Wed".to_string(),
919 4 => "Thu".to_string(),
920 5 => "Fri".to_string(),
921 6 => "Sat".to_string(),
924 'B' => match tm.tm_mon as int {
925 0 => "January".to_string(),
926 1 => "February".to_string(),
927 2 => "March".to_string(),
928 3 => "April".to_string(),
929 4 => "May".to_string(),
930 5 => "June".to_string(),
931 6 => "July".to_string(),
932 7 => "August".to_string(),
933 8 => "September".to_string(),
934 9 => "October".to_string(),
935 10 => "November".to_string(),
936 11 => "December".to_string(),
939 'b' | 'h' => match tm.tm_mon as int {
940 0 => "Jan".to_string(),
941 1 => "Feb".to_string(),
942 2 => "Mar".to_string(),
943 3 => "Apr".to_string(),
944 4 => "May".to_string(),
945 5 => "Jun".to_string(),
946 6 => "Jul".to_string(),
947 7 => "Aug".to_string(),
948 8 => "Sep".to_string(),
949 9 => "Oct".to_string(),
950 10 => "Nov".to_string(),
951 11 => "Dec".to_string(),
954 'C' => format_strbuf!("{:02d}", (tm.tm_year as int + 1900) / 100),
956 format_strbuf!("{} {} {} {} {}",
964 format_strbuf!("{}/{}/{}",
969 'd' => format_strbuf!("{:02d}", tm.tm_mday),
970 'e' => format_strbuf!("{:2d}", tm.tm_mday),
971 'f' => format_strbuf!("{:09d}", tm.tm_nsec),
973 format_strbuf!("{}-{}-{}",
978 'G' => iso_week('G', tm),
979 'g' => iso_week('g', tm),
980 'H' => format_strbuf!("{:02d}", tm.tm_hour),
982 let mut h = tm.tm_hour;
984 if h > 12 { h -= 12 }
985 format_strbuf!("{:02d}", h)
987 'j' => format_strbuf!("{:03d}", tm.tm_yday + 1),
988 'k' => format_strbuf!("{:2d}", tm.tm_hour),
990 let mut h = tm.tm_hour;
992 if h > 12 { h -= 12 }
993 format_strbuf!("{:2d}", h)
995 'M' => format_strbuf!("{:02d}", tm.tm_min),
996 'm' => format_strbuf!("{:02d}", tm.tm_mon + 1),
997 'n' => "\n".to_string(),
998 'P' => if (tm.tm_hour as int) < 12 { "am".to_string() } else { "pm".to_string() },
999 'p' => if (tm.tm_hour as int) < 12 { "AM".to_string() } else { "PM".to_string() },
1001 format_strbuf!("{}:{}",
1002 parse_type('H', tm),
1003 parse_type('M', tm))
1006 format_strbuf!("{}:{}:{} {}",
1007 parse_type('I', tm),
1008 parse_type('M', tm),
1009 parse_type('S', tm),
1010 parse_type('p', tm))
1012 'S' => format_strbuf!("{:02d}", tm.tm_sec),
1013 's' => format_strbuf!("{}", tm.to_timespec().sec),
1015 format_strbuf!("{}:{}:{}",
1016 parse_type('H', tm),
1017 parse_type('M', tm),
1018 parse_type('S', tm))
1020 't' => "\t".to_string(),
1021 'U' => format_strbuf!("{:02d}", (tm.tm_yday - tm.tm_wday + 7) / 7),
1023 let i = tm.tm_wday as int;
1024 (if i == 0 { 7 } else { i }).to_str().to_string()
1026 'V' => iso_week('V', tm),
1028 format_strbuf!("{}-{}-{}",
1029 parse_type('e', tm),
1030 parse_type('b', tm),
1031 parse_type('Y', tm))
1034 format_strbuf!("{:02d}",
1035 (tm.tm_yday - (tm.tm_wday - 1 + 7) % 7 + 7) / 7)
1037 'w' => (tm.tm_wday as int).to_str().to_string(),
1038 'Y' => (tm.tm_year as int + 1900).to_str().to_string(),
1039 'y' => format_strbuf!("{:02d}", (tm.tm_year as int + 1900) % 100),
1040 'Z' => "".to_string(), // FIXME(pcwalton): Implement this.
1042 let sign = if tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
1043 let mut m = num::abs(tm.tm_gmtoff) / 60_i32;
1046 format_strbuf!("{}{:02d}{:02d}", sign, h, m)
1048 '+' => tm.rfc3339(),
1049 '%' => "%".to_string(),
1054 let mut buf = Vec::new();
1056 let mut rdr = BufReader::new(format.as_bytes());
1059 let ch = match rdr.read(b) {
1065 rdr.read(b).unwrap();
1066 let s = parse_type(b[0] as char, tm);
1067 buf.push_all(s.as_bytes());
1069 ch => buf.push(ch as u8)
1073 str::from_utf8(buf.as_slice()).unwrap().to_string()
1079 use super::{Timespec, get_time, precise_time_ns, precise_time_s, tzset,
1080 at_utc, at, strptime};
1083 use std::result::{Err, Ok};
1084 use self::test::Bencher;
1087 fn set_time_zone() {
1089 // Windows crt doesn't see any environment variable set by
1090 // `SetEnvironmentVariable`, which `os::setenv` internally uses.
1091 // It is why we use `putenv` here.
1093 fn _putenv(envstring: *libc::c_char) -> libc::c_int;
1097 // Windows does not understand "America/Los_Angeles".
1098 // PST+08 may look wrong, but not! "PST" indicates
1099 // the name of timezone. "+08" means UTC = local + 08.
1100 "TZ=PST+08".with_c_str(|env| {
1106 #[cfg(not(windows))]
1107 fn set_time_zone() {
1109 os::setenv("TZ", "America/Los_Angeles");
1113 fn test_get_time() {
1114 static SOME_RECENT_DATE: i64 = 1325376000i64; // 2012-01-01T00:00:00Z
1115 static SOME_FUTURE_DATE: i64 = 1577836800i64; // 2020-01-01T00:00:00Z
1117 let tv1 = get_time();
1118 debug!("tv1={:?} sec + {:?} nsec", tv1.sec as uint, tv1.nsec as uint);
1120 assert!(tv1.sec > SOME_RECENT_DATE);
1121 assert!(tv1.nsec < 1000000000i32);
1123 let tv2 = get_time();
1124 debug!("tv2={:?} sec + {:?} nsec", tv2.sec as uint, tv2.nsec as uint);
1126 assert!(tv2.sec >= tv1.sec);
1127 assert!(tv2.sec < SOME_FUTURE_DATE);
1128 assert!(tv2.nsec < 1000000000i32);
1129 if tv2.sec == tv1.sec {
1130 assert!(tv2.nsec >= tv1.nsec);
1134 fn test_precise_time() {
1135 let s0 = precise_time_s();
1136 debug!("s0={} sec", f64::to_str_digits(s0, 9u));
1139 let ns0 = precise_time_ns();
1140 let ns1 = precise_time_ns();
1141 debug!("ns0={:?} ns", ns0);
1142 debug!("ns1={:?} ns", ns1);
1143 assert!(ns1 >= ns0);
1145 let ns2 = precise_time_ns();
1146 debug!("ns2={:?} ns", ns2);
1147 assert!(ns2 >= ns1);
1153 let time = Timespec::new(1234567890, 54321);
1154 let utc = at_utc(time);
1156 assert_eq!(utc.tm_sec, 30_i32);
1157 assert_eq!(utc.tm_min, 31_i32);
1158 assert_eq!(utc.tm_hour, 23_i32);
1159 assert_eq!(utc.tm_mday, 13_i32);
1160 assert_eq!(utc.tm_mon, 1_i32);
1161 assert_eq!(utc.tm_year, 109_i32);
1162 assert_eq!(utc.tm_wday, 5_i32);
1163 assert_eq!(utc.tm_yday, 43_i32);
1164 assert_eq!(utc.tm_isdst, 0_i32);
1165 assert_eq!(utc.tm_gmtoff, 0_i32);
1166 assert_eq!(utc.tm_nsec, 54321_i32);
1172 let time = Timespec::new(1234567890, 54321);
1173 let local = at(time);
1175 debug!("time_at: {:?}", local);
1177 assert_eq!(local.tm_sec, 30_i32);
1178 assert_eq!(local.tm_min, 31_i32);
1179 assert_eq!(local.tm_hour, 15_i32);
1180 assert_eq!(local.tm_mday, 13_i32);
1181 assert_eq!(local.tm_mon, 1_i32);
1182 assert_eq!(local.tm_year, 109_i32);
1183 assert_eq!(local.tm_wday, 5_i32);
1184 assert_eq!(local.tm_yday, 43_i32);
1185 assert_eq!(local.tm_isdst, 0_i32);
1186 assert_eq!(local.tm_gmtoff, -28800_i32);
1187 assert_eq!(local.tm_nsec, 54321_i32);
1190 fn test_to_timespec() {
1193 let time = Timespec::new(1234567890, 54321);
1194 let utc = at_utc(time);
1196 assert_eq!(utc.to_timespec(), time);
1197 assert_eq!(utc.to_local().to_timespec(), time);
1200 fn test_conversions() {
1203 let time = Timespec::new(1234567890, 54321);
1204 let utc = at_utc(time);
1205 let local = at(time);
1207 assert!(local.to_local() == local);
1208 assert!(local.to_utc() == utc);
1209 assert!(local.to_utc().to_local() == local);
1210 assert!(utc.to_utc() == utc);
1211 assert!(utc.to_local() == local);
1212 assert!(utc.to_local().to_utc() == utc);
1215 fn test_strptime() {
1218 match strptime("", "") {
1220 assert!(tm.tm_sec == 0_i32);
1221 assert!(tm.tm_min == 0_i32);
1222 assert!(tm.tm_hour == 0_i32);
1223 assert!(tm.tm_mday == 0_i32);
1224 assert!(tm.tm_mon == 0_i32);
1225 assert!(tm.tm_year == 0_i32);
1226 assert!(tm.tm_wday == 0_i32);
1227 assert!(tm.tm_isdst == 0_i32);
1228 assert!(tm.tm_gmtoff == 0_i32);
1229 assert!(tm.tm_nsec == 0_i32);
1234 let format = "%a %b %e %T.%f %Y";
1235 assert_eq!(strptime("", format), Err("Invalid time".to_string()));
1236 assert!(strptime("Fri Feb 13 15:31:30", format)
1237 == Err("Invalid time".to_string()));
1239 match strptime("Fri Feb 13 15:31:30.01234 2009", format) {
1242 assert!(tm.tm_sec == 30_i32);
1243 assert!(tm.tm_min == 31_i32);
1244 assert!(tm.tm_hour == 15_i32);
1245 assert!(tm.tm_mday == 13_i32);
1246 assert!(tm.tm_mon == 1_i32);
1247 assert!(tm.tm_year == 109_i32);
1248 assert!(tm.tm_wday == 5_i32);
1249 assert!(tm.tm_yday == 0_i32);
1250 assert!(tm.tm_isdst == 0_i32);
1251 assert!(tm.tm_gmtoff == 0_i32);
1252 assert!(tm.tm_nsec == 12340000_i32);
1256 fn test(s: &str, format: &str) -> bool {
1257 match strptime(s, format) {
1258 Ok(ref tm) => tm.strftime(format) == s.to_string(),
1264 "Sunday".to_string(),
1265 "Monday".to_string(),
1266 "Tuesday".to_string(),
1267 "Wednesday".to_string(),
1268 "Thursday".to_string(),
1269 "Friday".to_string(),
1270 "Saturday".to_string()
1272 for day in days.iter() {
1273 assert!(test(day.as_slice(), "%A"));
1285 for day in days.iter() {
1286 assert!(test(day.as_slice(), "%a"));
1290 "January".to_string(),
1291 "February".to_string(),
1292 "March".to_string(),
1293 "April".to_string(),
1297 "August".to_string(),
1298 "September".to_string(),
1299 "October".to_string(),
1300 "November".to_string(),
1301 "December".to_string()
1303 for day in months.iter() {
1304 assert!(test(day.as_slice(), "%B"));
1321 for day in months.iter() {
1322 assert!(test(day.as_slice(), "%b"));
1325 assert!(test("19", "%C"));
1326 assert!(test("Fri Feb 13 23:31:30 2009", "%c"));
1327 assert!(test("02/13/09", "%D"));
1328 assert!(test("03", "%d"));
1329 assert!(test("13", "%d"));
1330 assert!(test(" 3", "%e"));
1331 assert!(test("13", "%e"));
1332 assert!(test("2009-02-13", "%F"));
1333 assert!(test("03", "%H"));
1334 assert!(test("13", "%H"));
1335 assert!(test("03", "%I")); // FIXME (#2350): flesh out
1336 assert!(test("11", "%I")); // FIXME (#2350): flesh out
1337 assert!(test("044", "%j"));
1338 assert!(test(" 3", "%k"));
1339 assert!(test("13", "%k"));
1340 assert!(test(" 1", "%l"));
1341 assert!(test("11", "%l"));
1342 assert!(test("03", "%M"));
1343 assert!(test("13", "%M"));
1344 assert!(test("\n", "%n"));
1345 assert!(test("am", "%P"));
1346 assert!(test("pm", "%P"));
1347 assert!(test("AM", "%p"));
1348 assert!(test("PM", "%p"));
1349 assert!(test("23:31", "%R"));
1350 assert!(test("11:31:30 AM", "%r"));
1351 assert!(test("11:31:30 PM", "%r"));
1352 assert!(test("03", "%S"));
1353 assert!(test("13", "%S"));
1354 assert!(test("15:31:30", "%T"));
1355 assert!(test("\t", "%t"));
1356 assert!(test("1", "%u"));
1357 assert!(test("7", "%u"));
1358 assert!(test("13-Feb-2009", "%v"));
1359 assert!(test("0", "%w"));
1360 assert!(test("6", "%w"));
1361 assert!(test("2009", "%Y"));
1362 assert!(test("09", "%y"));
1363 assert!(strptime("-0000", "%z").unwrap().tm_gmtoff ==
1365 assert!(strptime("-0800", "%z").unwrap().tm_gmtoff ==
1367 assert!(test("%", "%%"));
1370 assert_eq!(strptime("360", "%Y-%m-%d"), Err("Invalid year".to_string()))
1376 let time = Timespec::new(1234567890, 54321);
1377 let utc = at_utc(time);
1378 let local = at(time);
1380 debug!("test_ctime: {:?} {:?}", utc.ctime(), local.ctime());
1382 assert_eq!(utc.ctime(), "Fri Feb 13 23:31:30 2009".to_string());
1383 assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1386 fn test_strftime() {
1389 let time = Timespec::new(1234567890, 54321);
1390 let utc = at_utc(time);
1391 let local = at(time);
1393 assert_eq!(local.strftime(""), "".to_string());
1394 assert_eq!(local.strftime("%A"), "Friday".to_string());
1395 assert_eq!(local.strftime("%a"), "Fri".to_string());
1396 assert_eq!(local.strftime("%B"), "February".to_string());
1397 assert_eq!(local.strftime("%b"), "Feb".to_string());
1398 assert_eq!(local.strftime("%C"), "20".to_string());
1399 assert_eq!(local.strftime("%c"), "Fri Feb 13 15:31:30 2009".to_string());
1400 assert_eq!(local.strftime("%D"), "02/13/09".to_string());
1401 assert_eq!(local.strftime("%d"), "13".to_string());
1402 assert_eq!(local.strftime("%e"), "13".to_string());
1403 assert_eq!(local.strftime("%f"), "000054321".to_string());
1404 assert_eq!(local.strftime("%F"), "2009-02-13".to_string());
1405 assert_eq!(local.strftime("%G"), "2009".to_string());
1406 assert_eq!(local.strftime("%g"), "09".to_string());
1407 assert_eq!(local.strftime("%H"), "15".to_string());
1408 assert_eq!(local.strftime("%I"), "03".to_string());
1409 assert_eq!(local.strftime("%j"), "044".to_string());
1410 assert_eq!(local.strftime("%k"), "15".to_string());
1411 assert_eq!(local.strftime("%l"), " 3".to_string());
1412 assert_eq!(local.strftime("%M"), "31".to_string());
1413 assert_eq!(local.strftime("%m"), "02".to_string());
1414 assert_eq!(local.strftime("%n"), "\n".to_string());
1415 assert_eq!(local.strftime("%P"), "pm".to_string());
1416 assert_eq!(local.strftime("%p"), "PM".to_string());
1417 assert_eq!(local.strftime("%R"), "15:31".to_string());
1418 assert_eq!(local.strftime("%r"), "03:31:30 PM".to_string());
1419 assert_eq!(local.strftime("%S"), "30".to_string());
1420 assert_eq!(local.strftime("%s"), "1234567890".to_string());
1421 assert_eq!(local.strftime("%T"), "15:31:30".to_string());
1422 assert_eq!(local.strftime("%t"), "\t".to_string());
1423 assert_eq!(local.strftime("%U"), "06".to_string());
1424 assert_eq!(local.strftime("%u"), "5".to_string());
1425 assert_eq!(local.strftime("%V"), "07".to_string());
1426 assert_eq!(local.strftime("%v"), "13-Feb-2009".to_string());
1427 assert_eq!(local.strftime("%W"), "06".to_string());
1428 assert_eq!(local.strftime("%w"), "5".to_string());
1429 assert_eq!(local.strftime("%X"), "15:31:30".to_string()); // FIXME (#2350): support locale
1430 assert_eq!(local.strftime("%x"), "02/13/09".to_string()); // FIXME (#2350): support locale
1431 assert_eq!(local.strftime("%Y"), "2009".to_string());
1432 assert_eq!(local.strftime("%y"), "09".to_string());
1433 assert_eq!(local.strftime("%+"), "2009-02-13T15:31:30-08:00".to_string());
1434 assert_eq!(local.strftime("%z"), "-0800".to_string());
1435 assert_eq!(local.strftime("%%"), "%".to_string());
1437 assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1438 assert_eq!(local.rfc822z(), "Fri, 13 Feb 2009 15:31:30 -0800".to_string());
1439 assert_eq!(local.rfc3339(), "2009-02-13T15:31:30-08:00".to_string());
1441 assert_eq!(utc.ctime(), "Fri Feb 13 23:31:30 2009".to_string());
1442 assert_eq!(utc.rfc822(), "Fri, 13 Feb 2009 23:31:30 GMT".to_string());
1443 assert_eq!(utc.rfc822z(), "Fri, 13 Feb 2009 23:31:30 -0000".to_string());
1444 assert_eq!(utc.rfc3339(), "2009-02-13T23:31:30Z".to_string());
1447 fn test_timespec_eq_ord() {
1448 let a = &Timespec::new(-2, 1);
1449 let b = &Timespec::new(-1, 2);
1450 let c = &Timespec::new(1, 2);
1451 let d = &Timespec::new(2, 1);
1452 let e = &Timespec::new(2, 1);
1479 #[ignore(cfg(target_os = "android"))] // FIXME #10958
1481 // The tests race on tzset. So instead of having many independent
1482 // tests, we will just call the functions now.
1484 test_precise_time();
1492 test_timespec_eq_ord();
1496 fn bench_precise_time_ns(b: &mut Bencher) {
1497 b.iter(|| precise_time_ns())