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"]
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/0.11.0/",
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;
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 }
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 #[cfg(target_os = "ios")]
127 unsafe fn os_get_time() -> (i64, i32) {
129 let mut tv = libc::timeval { tv_sec: 0, tv_usec: 0 };
130 imp::gettimeofday(&mut tv, ptr::mut_null());
131 (tv.tv_sec as i64, tv.tv_usec * 1000)
134 #[cfg(not(target_os = "macos"), not(target_os = "ios"), not(windows))]
135 unsafe fn os_get_time() -> (i64, i32) {
136 let mut tv = libc::timespec { tv_sec: 0, tv_nsec: 0 };
137 imp::clock_gettime(libc::CLOCK_REALTIME, &mut tv);
138 (tv.tv_sec as i64, tv.tv_nsec as i32)
144 * Returns the current value of a high-resolution performance counter
145 * in nanoseconds since an unspecified epoch.
147 pub fn precise_time_ns() -> u64 {
148 return os_precise_time_ns();
151 fn os_precise_time_ns() -> u64 {
152 let mut ticks_per_s = 0;
154 libc::QueryPerformanceFrequency(&mut ticks_per_s)
156 let ticks_per_s = if ticks_per_s == 0 {1} else {ticks_per_s};
159 libc::QueryPerformanceCounter(&mut ticks)
162 return (ticks as u64 * 1000000000) / (ticks_per_s as u64);
165 #[cfg(target_os = "macos")]
166 #[cfg(target_os = "ios")]
167 fn os_precise_time_ns() -> u64 {
168 static mut TIMEBASE: libc::mach_timebase_info = libc::mach_timebase_info { numer: 0,
170 static mut ONCE: std::sync::Once = std::sync::ONCE_INIT;
173 imp::mach_timebase_info(&mut TIMEBASE);
175 let time = imp::mach_absolute_time();
176 time * TIMEBASE.numer as u64 / TIMEBASE.denom as u64
180 #[cfg(not(windows), not(target_os = "macos"), not(target_os = "ios"))]
181 fn os_precise_time_ns() -> u64 {
182 let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
184 imp::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts);
186 return (ts.tv_sec as u64) * 1000000000 + (ts.tv_nsec as u64)
192 * Returns the current value of a high-resolution performance counter
193 * in seconds since an unspecified epoch.
195 pub fn precise_time_s() -> f64 {
196 return (precise_time_ns() as f64) / 1000000000.;
201 rustrt::rust_tzset();
205 /// Holds a calendar date and time broken down into its components (year, month, day, and so on),
206 /// also called a broken-down time value.
207 #[deriving(Clone, PartialEq, Show)]
209 /// Seconds after the minute – [0, 60]
212 /// Minutes after the hour – [0, 59]
215 /// Hours after midnight – [0, 23]
218 /// Day of the month – [1, 31]
221 /// Months since January – [0, 11]
227 /// Days since Sunday – [0, 6]. 0 = Sunday, 1 = Monday, …, 6 = Saturday.
230 /// Days since January 1 – [0, 365]
233 /// Daylight Saving Time flag.
235 /// This value is positive if Daylight Saving Time is in effect, zero if Daylight Saving Time
236 /// is not in effect, and negative if this information is not available.
239 /// Identifies the time zone that was used to compute this broken-down time value, including any
240 /// adjustment for Daylight Saving Time. This is the number of seconds east of UTC. For example,
241 /// for U.S. Pacific Daylight Time, the value is -7*60*60 = -25200.
244 /// Nanoseconds after the second – [0, 10<sup>9</sup> - 1]
248 pub fn empty_tm() -> Tm {
264 /// Returns the specified time in UTC
265 pub fn at_utc(clock: Timespec) -> Tm {
267 let Timespec { sec, nsec } = clock;
268 let mut tm = empty_tm();
269 rustrt::rust_gmtime(sec, nsec, &mut tm);
274 /// Returns the current time in UTC
275 pub fn now_utc() -> Tm {
279 /// Returns the specified time in the local timezone
280 pub fn at(clock: Timespec) -> Tm {
282 let Timespec { sec, nsec } = clock;
283 let mut tm = empty_tm();
284 rustrt::rust_localtime(sec, nsec, &mut tm);
289 /// Returns the current time in the local timezone
296 /// Convert time to the seconds from January 1, 1970
297 pub fn to_timespec(&self) -> Timespec {
299 let sec = match self.tm_gmtoff {
300 0_i32 => rustrt::rust_timegm(self),
301 _ => rustrt::rust_mktime(self)
304 Timespec::new(sec, self.tm_nsec)
308 /// Convert time to the local timezone
309 pub fn to_local(&self) -> Tm {
310 at(self.to_timespec())
313 /// Convert time to the UTC
314 pub fn to_utc(&self) -> Tm {
315 at_utc(self.to_timespec())
319 * Returns a time string formatted according to the `asctime` format in ISO
320 * C, in the local timezone.
322 * Example: "Thu Jan 1 00:00:00 1970"
324 pub fn ctime(&self) -> String {
325 self.to_local().asctime()
329 * Returns a time string formatted according to the `asctime` format in ISO
332 * Example: "Thu Jan 1 00:00:00 1970"
334 pub fn asctime(&self) -> String {
338 /// Formats the time according to the format string.
339 pub fn strftime(&self, format: &str) -> String {
340 strftime(format, self)
344 * Returns a time string formatted according to RFC 822.
346 * local: "Thu, 22 Mar 2012 07:53:18 PST"
347 * utc: "Thu, 22 Mar 2012 14:53:18 GMT"
349 pub fn rfc822(&self) -> String {
350 if self.tm_gmtoff == 0_i32 {
351 self.strftime("%a, %d %b %Y %T GMT")
353 self.strftime("%a, %d %b %Y %T %Z")
358 * Returns a time string formatted according to RFC 822 with Zulu time.
360 * local: "Thu, 22 Mar 2012 07:53:18 -0700"
361 * utc: "Thu, 22 Mar 2012 14:53:18 -0000"
363 pub fn rfc822z(&self) -> String {
364 self.strftime("%a, %d %b %Y %T %z")
368 * Returns a time string formatted according to RFC 3999. RFC 3999 is
369 * compatible with ISO 8601.
371 * local: "2012-02-22T07:53:18-07:00"
372 * utc: "2012-02-22T14:53:18Z"
374 pub fn rfc3339(&self) -> String {
375 if self.tm_gmtoff == 0_i32 {
376 self.strftime("%Y-%m-%dT%H:%M:%SZ")
378 let s = self.strftime("%Y-%m-%dT%H:%M:%S");
379 let sign = if self.tm_gmtoff > 0_i32 { '+' } else { '-' };
380 let mut m = num::abs(self.tm_gmtoff) / 60_i32;
383 format!("{}{}{:02d}:{:02d}", s, sign, h as int, m as int)
388 /// Parses the time from the string according to the format string.
389 pub fn strptime(s: &str, format: &str) -> Result<Tm, String> {
390 fn match_str(s: &str, pos: uint, needle: &str) -> bool {
392 for ch in needle.bytes() {
393 if s.as_bytes()[i] != ch {
401 fn match_strs(ss: &str, pos: uint, strs: &[(String, i32)])
402 -> Option<(i32, uint)> {
404 let len = strs.len();
406 match strs[i] { // can't use let due to let-pattern bugs
407 (ref needle, value) => {
408 if match_str(ss, pos, needle.as_slice()) {
409 return Some((value, pos + needle.len()));
419 fn match_digits(ss: &str, pos: uint, digits: uint, ws: bool)
420 -> Option<(i32, uint)> {
423 let mut value = 0_i32;
430 let range = ss.char_range_at(pos);
435 value = value * 10_i32 + (range.ch as i32 - '0' as i32);
446 fn match_fractional_seconds(ss: &str, pos: uint) -> (i32, uint) {
448 let mut value = 0_i32;
449 let mut multiplier = NSEC_PER_SEC / 10;
456 let range = ss.char_range_at(pos);
461 // This will drop digits after the nanoseconds place
462 let digit = range.ch as i32 - '0' as i32;
463 value += digit * multiplier;
473 fn match_digits_in_range(ss: &str, pos: uint, digits: uint, ws: bool,
474 min: i32, max: i32) -> Option<(i32, uint)> {
475 match match_digits(ss, pos, digits, ws) {
476 Some((val, pos)) if val >= min && val <= max => {
483 fn parse_char(s: &str, pos: uint, c: char) -> Result<uint, String> {
484 let range = s.char_range_at(pos);
489 Err(format!("Expected {}, found {}",
491 str::from_char(range.ch)))
495 fn parse_type(s: &str, pos: uint, ch: char, tm: &mut Tm)
496 -> Result<uint, String> {
498 'A' => match match_strs(s, pos, [
499 ("Sunday".to_string(), 0_i32),
500 ("Monday".to_string(), 1_i32),
501 ("Tuesday".to_string(), 2_i32),
502 ("Wednesday".to_string(), 3_i32),
503 ("Thursday".to_string(), 4_i32),
504 ("Friday".to_string(), 5_i32),
505 ("Saturday".to_string(), 6_i32)
507 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
508 None => Err("Invalid day".to_string())
510 'a' => match match_strs(s, pos, [
511 ("Sun".to_string(), 0_i32),
512 ("Mon".to_string(), 1_i32),
513 ("Tue".to_string(), 2_i32),
514 ("Wed".to_string(), 3_i32),
515 ("Thu".to_string(), 4_i32),
516 ("Fri".to_string(), 5_i32),
517 ("Sat".to_string(), 6_i32)
519 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
520 None => Err("Invalid day".to_string())
522 'B' => match match_strs(s, pos, [
523 ("January".to_string(), 0_i32),
524 ("February".to_string(), 1_i32),
525 ("March".to_string(), 2_i32),
526 ("April".to_string(), 3_i32),
527 ("May".to_string(), 4_i32),
528 ("June".to_string(), 5_i32),
529 ("July".to_string(), 6_i32),
530 ("August".to_string(), 7_i32),
531 ("September".to_string(), 8_i32),
532 ("October".to_string(), 9_i32),
533 ("November".to_string(), 10_i32),
534 ("December".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 'b' | 'h' => match match_strs(s, pos, [
540 ("Jan".to_string(), 0_i32),
541 ("Feb".to_string(), 1_i32),
542 ("Mar".to_string(), 2_i32),
543 ("Apr".to_string(), 3_i32),
544 ("May".to_string(), 4_i32),
545 ("Jun".to_string(), 5_i32),
546 ("Jul".to_string(), 6_i32),
547 ("Aug".to_string(), 7_i32),
548 ("Sep".to_string(), 8_i32),
549 ("Oct".to_string(), 9_i32),
550 ("Nov".to_string(), 10_i32),
551 ("Dec".to_string(), 11_i32)
553 Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
554 None => Err("Invalid month".to_string())
556 'C' => match match_digits_in_range(s, pos, 2u, false, 0_i32,
560 tm.tm_year += (v * 100_i32) - 1900_i32;
563 None => Err("Invalid year".to_string())
566 parse_type(s, pos, 'a', &mut *tm)
567 .and_then(|pos| parse_char(s, pos, ' '))
568 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
569 .and_then(|pos| parse_char(s, pos, ' '))
570 .and_then(|pos| parse_type(s, pos, 'e', &mut *tm))
571 .and_then(|pos| parse_char(s, pos, ' '))
572 .and_then(|pos| parse_type(s, pos, 'T', &mut *tm))
573 .and_then(|pos| parse_char(s, pos, ' '))
574 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
577 parse_type(s, pos, 'm', &mut *tm)
578 .and_then(|pos| parse_char(s, pos, '/'))
579 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
580 .and_then(|pos| parse_char(s, pos, '/'))
581 .and_then(|pos| parse_type(s, pos, 'y', &mut *tm))
583 'd' => match match_digits_in_range(s, pos, 2u, false, 1_i32,
585 Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
586 None => Err("Invalid day of the month".to_string())
588 'e' => match match_digits_in_range(s, pos, 2u, true, 1_i32,
590 Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
591 None => Err("Invalid day of the month".to_string())
594 let (val, pos) = match_fractional_seconds(s, pos);
599 parse_type(s, pos, 'Y', &mut *tm)
600 .and_then(|pos| parse_char(s, pos, '-'))
601 .and_then(|pos| parse_type(s, pos, 'm', &mut *tm))
602 .and_then(|pos| parse_char(s, pos, '-'))
603 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
606 match match_digits_in_range(s, pos, 2u, false, 0_i32, 23_i32) {
607 Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
608 None => Err("Invalid hour".to_string())
612 match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
615 tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
618 None => Err("Invalid hour".to_string())
622 match match_digits_in_range(s, pos, 3u, false, 1_i32, 366_i32) {
625 tm.tm_yday = v - 1_i32;
628 None => Err("Invalid day of year".to_string())
632 match match_digits_in_range(s, pos, 2u, true, 0_i32, 23_i32) {
633 Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
634 None => Err("Invalid hour".to_string())
638 match match_digits_in_range(s, pos, 2u, true, 1_i32, 12_i32) {
641 tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
644 None => Err("Invalid hour".to_string())
648 match match_digits_in_range(s, pos, 2u, false, 0_i32, 59_i32) {
649 Some(item) => { let (v, pos) = item; tm.tm_min = v; Ok(pos) }
650 None => Err("Invalid minute".to_string())
654 match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
657 tm.tm_mon = v - 1_i32;
660 None => Err("Invalid month".to_string())
663 'n' => parse_char(s, pos, '\n'),
664 'P' => match match_strs(s, pos,
665 [("am".to_string(), 0_i32), ("pm".to_string(), 12_i32)]) {
667 Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
668 None => Err("Invalid hour".to_string())
670 'p' => match match_strs(s, pos,
671 [("AM".to_string(), 0_i32), ("PM".to_string(), 12_i32)]) {
673 Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
674 None => Err("Invalid hour".to_string())
677 parse_type(s, pos, 'H', &mut *tm)
678 .and_then(|pos| parse_char(s, pos, ':'))
679 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
682 parse_type(s, pos, 'I', &mut *tm)
683 .and_then(|pos| parse_char(s, pos, ':'))
684 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
685 .and_then(|pos| parse_char(s, pos, ':'))
686 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
687 .and_then(|pos| parse_char(s, pos, ' '))
688 .and_then(|pos| parse_type(s, pos, 'p', &mut *tm))
691 match match_digits_in_range(s, pos, 2u, false, 0_i32, 60_i32) {
697 None => Err("Invalid second".to_string())
702 parse_type(s, pos, 'H', &mut *tm)
703 .and_then(|pos| parse_char(s, pos, ':'))
704 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
705 .and_then(|pos| parse_char(s, pos, ':'))
706 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
708 't' => parse_char(s, pos, '\t'),
710 match match_digits_in_range(s, pos, 1u, false, 1_i32, 7_i32) {
713 tm.tm_wday = if v == 7 { 0 } else { v };
716 None => Err("Invalid day of week".to_string())
720 parse_type(s, pos, 'e', &mut *tm)
721 .and_then(|pos| parse_char(s, pos, '-'))
722 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
723 .and_then(|pos| parse_char(s, pos, '-'))
724 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
728 match match_digits_in_range(s, pos, 1u, false, 0_i32, 6_i32) {
729 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
730 None => Err("Invalid day of week".to_string())
734 match match_digits(s, pos, 4u, false) {
737 tm.tm_year = v - 1900_i32;
740 None => Err("Invalid year".to_string())
744 match match_digits_in_range(s, pos, 2u, false, 0_i32, 99_i32) {
750 None => Err("Invalid year".to_string())
754 if match_str(s, pos, "UTC") || match_str(s, pos, "GMT") {
755 tm.tm_gmtoff = 0_i32;
758 // It's odd, but to maintain compatibility with c's
759 // strptime we ignore the timezone.
763 let range = s.char_range_at(pos);
765 if range.ch == ' ' { break; }
772 let range = s.char_range_at(pos);
774 if range.ch == '+' || range.ch == '-' {
775 match match_digits(s, range.next, 4u, false) {
779 tm.tm_gmtoff = 0_i32;
784 None => Err("Invalid zone offset".to_string())
787 Err("Invalid zone offset".to_string())
790 '%' => parse_char(s, pos, '%'),
792 Err(format!("unknown formatting type: {}", str::from_char(ch)))
797 let mut rdr = BufReader::new(format.as_bytes());
813 let mut result = Err("Invalid time".to_string());
816 let range = s.char_range_at(pos);
818 let next = range.next;
821 let c = match rdr.read(buf) {
822 Ok(..) => buf[0] as char,
827 let ch = match rdr.read(buf) {
828 Ok(..) => buf[0] as char,
831 match parse_type(s, pos, ch, &mut tm) {
832 Ok(next) => pos = next,
833 Err(e) => { result = Err(e); break; }
843 if pos == len && rdr.tell().unwrap() == format.len() as u64 {
853 tm_isdst: tm.tm_isdst,
854 tm_gmtoff: tm.tm_gmtoff,
860 /// Formats the time according to the format string.
861 pub fn strftime(format: &str, tm: &Tm) -> String {
862 fn days_in_year(year: int) -> i32 {
863 if (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) {
864 366 /* Days in a leap year */
866 365 /* Days in a non-leap year */
870 fn iso_week_days(yday: i32, wday: i32) -> int {
871 /* The number of days from the first day of the first ISO week of this
872 * year to the year day YDAY with week day WDAY.
873 * ISO weeks start on Monday. The first ISO week has the year's first
875 * YDAY may be as small as yday_minimum.
877 let yday: int = yday as int;
878 let wday: int = wday as int;
879 let iso_week_start_wday: int = 1; /* Monday */
880 let iso_week1_wday: int = 4; /* Thursday */
881 let yday_minimum: int = 366;
882 /* Add enough to the first operand of % to make it nonnegative. */
883 let big_enough_multiple_of_7: int = (yday_minimum / 7 + 2) * 7;
885 yday - (yday - wday + iso_week1_wday + big_enough_multiple_of_7) % 7
886 + iso_week1_wday - iso_week_start_wday
889 fn iso_week(ch:char, tm: &Tm) -> String {
890 let mut year: int = tm.tm_year as int + 1900;
891 let mut days: int = iso_week_days (tm.tm_yday, tm.tm_wday);
894 /* This ISO week belongs to the previous year. */
896 days = iso_week_days (tm.tm_yday + (days_in_year(year)), tm.tm_wday);
898 let d: int = iso_week_days (tm.tm_yday - (days_in_year(year)),
901 /* This ISO week belongs to the next year. */
908 'G' => format!("{}", year),
909 'g' => format!("{:02d}", (year % 100 + 100) % 100),
910 'V' => format!("{:02d}", days / 7 + 1),
915 fn parse_type(ch: char, tm: &Tm) -> String {
917 format!("strftime: can't understand this format {} ", ch)
920 'A' => match tm.tm_wday as int {
921 0 => "Sunday".to_string(),
922 1 => "Monday".to_string(),
923 2 => "Tuesday".to_string(),
924 3 => "Wednesday".to_string(),
925 4 => "Thursday".to_string(),
926 5 => "Friday".to_string(),
927 6 => "Saturday".to_string(),
930 'a' => match tm.tm_wday as int {
931 0 => "Sun".to_string(),
932 1 => "Mon".to_string(),
933 2 => "Tue".to_string(),
934 3 => "Wed".to_string(),
935 4 => "Thu".to_string(),
936 5 => "Fri".to_string(),
937 6 => "Sat".to_string(),
940 'B' => match tm.tm_mon as int {
941 0 => "January".to_string(),
942 1 => "February".to_string(),
943 2 => "March".to_string(),
944 3 => "April".to_string(),
945 4 => "May".to_string(),
946 5 => "June".to_string(),
947 6 => "July".to_string(),
948 7 => "August".to_string(),
949 8 => "September".to_string(),
950 9 => "October".to_string(),
951 10 => "November".to_string(),
952 11 => "December".to_string(),
955 'b' | 'h' => match tm.tm_mon as int {
956 0 => "Jan".to_string(),
957 1 => "Feb".to_string(),
958 2 => "Mar".to_string(),
959 3 => "Apr".to_string(),
960 4 => "May".to_string(),
961 5 => "Jun".to_string(),
962 6 => "Jul".to_string(),
963 7 => "Aug".to_string(),
964 8 => "Sep".to_string(),
965 9 => "Oct".to_string(),
966 10 => "Nov".to_string(),
967 11 => "Dec".to_string(),
970 'C' => format!("{:02d}", (tm.tm_year as int + 1900) / 100),
972 format!("{} {} {} {} {}",
985 'd' => format!("{:02d}", tm.tm_mday),
986 'e' => format!("{:2d}", tm.tm_mday),
987 'f' => format!("{:09d}", tm.tm_nsec),
994 'G' => iso_week('G', tm),
995 'g' => iso_week('g', tm),
996 'H' => format!("{:02d}", tm.tm_hour),
998 let mut h = tm.tm_hour;
1000 if h > 12 { h -= 12 }
1001 format!("{:02d}", h)
1003 'j' => format!("{:03d}", tm.tm_yday + 1),
1004 'k' => format!("{:2d}", tm.tm_hour),
1006 let mut h = tm.tm_hour;
1007 if h == 0 { h = 12 }
1008 if h > 12 { h -= 12 }
1011 'M' => format!("{:02d}", tm.tm_min),
1012 'm' => format!("{:02d}", tm.tm_mon + 1),
1013 'n' => "\n".to_string(),
1014 'P' => if (tm.tm_hour as int) < 12 { "am".to_string() } else { "pm".to_string() },
1015 'p' => if (tm.tm_hour as int) < 12 { "AM".to_string() } else { "PM".to_string() },
1018 parse_type('H', tm),
1019 parse_type('M', tm))
1022 format!("{}:{}:{} {}",
1023 parse_type('I', tm),
1024 parse_type('M', tm),
1025 parse_type('S', tm),
1026 parse_type('p', tm))
1028 'S' => format!("{:02d}", tm.tm_sec),
1029 's' => format!("{}", tm.to_timespec().sec),
1032 parse_type('H', tm),
1033 parse_type('M', tm),
1034 parse_type('S', tm))
1036 't' => "\t".to_string(),
1037 'U' => format!("{:02d}", (tm.tm_yday - tm.tm_wday + 7) / 7),
1039 let i = tm.tm_wday as int;
1040 (if i == 0 { 7 } else { i }).to_str()
1042 'V' => iso_week('V', tm),
1045 parse_type('e', tm),
1046 parse_type('b', tm),
1047 parse_type('Y', tm))
1051 (tm.tm_yday - (tm.tm_wday - 1 + 7) % 7 + 7) / 7)
1053 'w' => (tm.tm_wday as int).to_str(),
1054 'Y' => (tm.tm_year as int + 1900).to_str(),
1055 'y' => format!("{:02d}", (tm.tm_year as int + 1900) % 100),
1056 'Z' => "".to_string(), // FIXME(pcwalton): Implement this.
1058 let sign = if tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
1059 let mut m = num::abs(tm.tm_gmtoff) / 60_i32;
1062 format!("{}{:02d}{:02d}", sign, h, m)
1064 '+' => tm.rfc3339(),
1065 '%' => "%".to_string(),
1070 let mut buf = Vec::new();
1072 let mut rdr = BufReader::new(format.as_bytes());
1075 let ch = match rdr.read(b) {
1081 rdr.read(b).unwrap();
1082 let s = parse_type(b[0] as char, tm);
1083 buf.push_all(s.as_bytes());
1085 ch => buf.push(ch as u8)
1089 str::from_utf8(buf.as_slice()).unwrap().to_string()
1095 use super::{Timespec, get_time, precise_time_ns, precise_time_s, tzset,
1096 at_utc, at, strptime};
1099 use std::result::{Err, Ok};
1100 use self::test::Bencher;
1103 fn set_time_zone() {
1105 // Windows crt doesn't see any environment variable set by
1106 // `SetEnvironmentVariable`, which `os::setenv` internally uses.
1107 // It is why we use `putenv` here.
1109 fn _putenv(envstring: *const libc::c_char) -> libc::c_int;
1113 // Windows does not understand "America/Los_Angeles".
1114 // PST+08 may look wrong, but not! "PST" indicates
1115 // the name of timezone. "+08" means UTC = local + 08.
1116 "TZ=PST+08".with_c_str(|env| {
1122 #[cfg(not(windows))]
1123 fn set_time_zone() {
1125 os::setenv("TZ", "America/Los_Angeles");
1129 fn test_get_time() {
1130 static SOME_RECENT_DATE: i64 = 1325376000i64; // 2012-01-01T00:00:00Z
1131 static SOME_FUTURE_DATE: i64 = 1577836800i64; // 2020-01-01T00:00:00Z
1133 let tv1 = get_time();
1134 debug!("tv1={:?} sec + {:?} nsec", tv1.sec as uint, tv1.nsec as uint);
1136 assert!(tv1.sec > SOME_RECENT_DATE);
1137 assert!(tv1.nsec < 1000000000i32);
1139 let tv2 = get_time();
1140 debug!("tv2={:?} sec + {:?} nsec", tv2.sec as uint, tv2.nsec as uint);
1142 assert!(tv2.sec >= tv1.sec);
1143 assert!(tv2.sec < SOME_FUTURE_DATE);
1144 assert!(tv2.nsec < 1000000000i32);
1145 if tv2.sec == tv1.sec {
1146 assert!(tv2.nsec >= tv1.nsec);
1150 fn test_precise_time() {
1151 let s0 = precise_time_s();
1152 debug!("s0={} sec", f64::to_str_digits(s0, 9u));
1155 let ns0 = precise_time_ns();
1156 let ns1 = precise_time_ns();
1157 debug!("ns0={:?} ns", ns0);
1158 debug!("ns1={:?} ns", ns1);
1159 assert!(ns1 >= ns0);
1161 let ns2 = precise_time_ns();
1162 debug!("ns2={:?} ns", ns2);
1163 assert!(ns2 >= ns1);
1169 let time = Timespec::new(1234567890, 54321);
1170 let utc = at_utc(time);
1172 assert_eq!(utc.tm_sec, 30_i32);
1173 assert_eq!(utc.tm_min, 31_i32);
1174 assert_eq!(utc.tm_hour, 23_i32);
1175 assert_eq!(utc.tm_mday, 13_i32);
1176 assert_eq!(utc.tm_mon, 1_i32);
1177 assert_eq!(utc.tm_year, 109_i32);
1178 assert_eq!(utc.tm_wday, 5_i32);
1179 assert_eq!(utc.tm_yday, 43_i32);
1180 assert_eq!(utc.tm_isdst, 0_i32);
1181 assert_eq!(utc.tm_gmtoff, 0_i32);
1182 assert_eq!(utc.tm_nsec, 54321_i32);
1188 let time = Timespec::new(1234567890, 54321);
1189 let local = at(time);
1191 debug!("time_at: {:?}", local);
1193 assert_eq!(local.tm_sec, 30_i32);
1194 assert_eq!(local.tm_min, 31_i32);
1195 assert_eq!(local.tm_hour, 15_i32);
1196 assert_eq!(local.tm_mday, 13_i32);
1197 assert_eq!(local.tm_mon, 1_i32);
1198 assert_eq!(local.tm_year, 109_i32);
1199 assert_eq!(local.tm_wday, 5_i32);
1200 assert_eq!(local.tm_yday, 43_i32);
1201 assert_eq!(local.tm_isdst, 0_i32);
1202 assert_eq!(local.tm_gmtoff, -28800_i32);
1203 assert_eq!(local.tm_nsec, 54321_i32);
1206 fn test_to_timespec() {
1209 let time = Timespec::new(1234567890, 54321);
1210 let utc = at_utc(time);
1212 assert_eq!(utc.to_timespec(), time);
1213 assert_eq!(utc.to_local().to_timespec(), time);
1216 fn test_conversions() {
1219 let time = Timespec::new(1234567890, 54321);
1220 let utc = at_utc(time);
1221 let local = at(time);
1223 assert!(local.to_local() == local);
1224 assert!(local.to_utc() == utc);
1225 assert!(local.to_utc().to_local() == local);
1226 assert!(utc.to_utc() == utc);
1227 assert!(utc.to_local() == local);
1228 assert!(utc.to_local().to_utc() == utc);
1231 fn test_strptime() {
1234 match strptime("", "") {
1236 assert!(tm.tm_sec == 0_i32);
1237 assert!(tm.tm_min == 0_i32);
1238 assert!(tm.tm_hour == 0_i32);
1239 assert!(tm.tm_mday == 0_i32);
1240 assert!(tm.tm_mon == 0_i32);
1241 assert!(tm.tm_year == 0_i32);
1242 assert!(tm.tm_wday == 0_i32);
1243 assert!(tm.tm_isdst == 0_i32);
1244 assert!(tm.tm_gmtoff == 0_i32);
1245 assert!(tm.tm_nsec == 0_i32);
1250 let format = "%a %b %e %T.%f %Y";
1251 assert_eq!(strptime("", format), Err("Invalid time".to_string()));
1252 assert!(strptime("Fri Feb 13 15:31:30", format)
1253 == Err("Invalid time".to_string()));
1255 match strptime("Fri Feb 13 15:31:30.01234 2009", format) {
1258 assert!(tm.tm_sec == 30_i32);
1259 assert!(tm.tm_min == 31_i32);
1260 assert!(tm.tm_hour == 15_i32);
1261 assert!(tm.tm_mday == 13_i32);
1262 assert!(tm.tm_mon == 1_i32);
1263 assert!(tm.tm_year == 109_i32);
1264 assert!(tm.tm_wday == 5_i32);
1265 assert!(tm.tm_yday == 0_i32);
1266 assert!(tm.tm_isdst == 0_i32);
1267 assert!(tm.tm_gmtoff == 0_i32);
1268 assert!(tm.tm_nsec == 12340000_i32);
1272 fn test(s: &str, format: &str) -> bool {
1273 match strptime(s, format) {
1274 Ok(ref tm) => tm.strftime(format) == s.to_string(),
1280 "Sunday".to_string(),
1281 "Monday".to_string(),
1282 "Tuesday".to_string(),
1283 "Wednesday".to_string(),
1284 "Thursday".to_string(),
1285 "Friday".to_string(),
1286 "Saturday".to_string()
1288 for day in days.iter() {
1289 assert!(test(day.as_slice(), "%A"));
1301 for day in days.iter() {
1302 assert!(test(day.as_slice(), "%a"));
1306 "January".to_string(),
1307 "February".to_string(),
1308 "March".to_string(),
1309 "April".to_string(),
1313 "August".to_string(),
1314 "September".to_string(),
1315 "October".to_string(),
1316 "November".to_string(),
1317 "December".to_string()
1319 for day in months.iter() {
1320 assert!(test(day.as_slice(), "%B"));
1337 for day in months.iter() {
1338 assert!(test(day.as_slice(), "%b"));
1341 assert!(test("19", "%C"));
1342 assert!(test("Fri Feb 13 23:31:30 2009", "%c"));
1343 assert!(test("02/13/09", "%D"));
1344 assert!(test("03", "%d"));
1345 assert!(test("13", "%d"));
1346 assert!(test(" 3", "%e"));
1347 assert!(test("13", "%e"));
1348 assert!(test("2009-02-13", "%F"));
1349 assert!(test("03", "%H"));
1350 assert!(test("13", "%H"));
1351 assert!(test("03", "%I")); // FIXME (#2350): flesh out
1352 assert!(test("11", "%I")); // FIXME (#2350): flesh out
1353 assert!(test("044", "%j"));
1354 assert!(test(" 3", "%k"));
1355 assert!(test("13", "%k"));
1356 assert!(test(" 1", "%l"));
1357 assert!(test("11", "%l"));
1358 assert!(test("03", "%M"));
1359 assert!(test("13", "%M"));
1360 assert!(test("\n", "%n"));
1361 assert!(test("am", "%P"));
1362 assert!(test("pm", "%P"));
1363 assert!(test("AM", "%p"));
1364 assert!(test("PM", "%p"));
1365 assert!(test("23:31", "%R"));
1366 assert!(test("11:31:30 AM", "%r"));
1367 assert!(test("11:31:30 PM", "%r"));
1368 assert!(test("03", "%S"));
1369 assert!(test("13", "%S"));
1370 assert!(test("15:31:30", "%T"));
1371 assert!(test("\t", "%t"));
1372 assert!(test("1", "%u"));
1373 assert!(test("7", "%u"));
1374 assert!(test("13-Feb-2009", "%v"));
1375 assert!(test("0", "%w"));
1376 assert!(test("6", "%w"));
1377 assert!(test("2009", "%Y"));
1378 assert!(test("09", "%y"));
1379 assert!(strptime("-0000", "%z").unwrap().tm_gmtoff ==
1381 assert!(strptime("-0800", "%z").unwrap().tm_gmtoff ==
1383 assert!(test("%", "%%"));
1386 assert_eq!(strptime("360", "%Y-%m-%d"), Err("Invalid year".to_string()))
1392 let time = Timespec::new(1234567890, 54321);
1393 let utc = at_utc(time);
1394 let local = at(time);
1396 debug!("test_ctime: {:?} {:?}", utc.asctime(), local.asctime());
1398 assert_eq!(utc.asctime(), "Fri Feb 13 23:31:30 2009".to_string());
1399 assert_eq!(local.asctime(), "Fri Feb 13 15:31:30 2009".to_string());
1405 let time = Timespec::new(1234567890, 54321);
1406 let utc = at_utc(time);
1407 let local = at(time);
1409 debug!("test_ctime: {:?} {:?}", utc.ctime(), local.ctime());
1411 assert_eq!(utc.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1412 assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1415 fn test_strftime() {
1418 let time = Timespec::new(1234567890, 54321);
1419 let utc = at_utc(time);
1420 let local = at(time);
1422 assert_eq!(local.strftime(""), "".to_string());
1423 assert_eq!(local.strftime("%A"), "Friday".to_string());
1424 assert_eq!(local.strftime("%a"), "Fri".to_string());
1425 assert_eq!(local.strftime("%B"), "February".to_string());
1426 assert_eq!(local.strftime("%b"), "Feb".to_string());
1427 assert_eq!(local.strftime("%C"), "20".to_string());
1428 assert_eq!(local.strftime("%c"), "Fri Feb 13 15:31:30 2009".to_string());
1429 assert_eq!(local.strftime("%D"), "02/13/09".to_string());
1430 assert_eq!(local.strftime("%d"), "13".to_string());
1431 assert_eq!(local.strftime("%e"), "13".to_string());
1432 assert_eq!(local.strftime("%f"), "000054321".to_string());
1433 assert_eq!(local.strftime("%F"), "2009-02-13".to_string());
1434 assert_eq!(local.strftime("%G"), "2009".to_string());
1435 assert_eq!(local.strftime("%g"), "09".to_string());
1436 assert_eq!(local.strftime("%H"), "15".to_string());
1437 assert_eq!(local.strftime("%I"), "03".to_string());
1438 assert_eq!(local.strftime("%j"), "044".to_string());
1439 assert_eq!(local.strftime("%k"), "15".to_string());
1440 assert_eq!(local.strftime("%l"), " 3".to_string());
1441 assert_eq!(local.strftime("%M"), "31".to_string());
1442 assert_eq!(local.strftime("%m"), "02".to_string());
1443 assert_eq!(local.strftime("%n"), "\n".to_string());
1444 assert_eq!(local.strftime("%P"), "pm".to_string());
1445 assert_eq!(local.strftime("%p"), "PM".to_string());
1446 assert_eq!(local.strftime("%R"), "15:31".to_string());
1447 assert_eq!(local.strftime("%r"), "03:31:30 PM".to_string());
1448 assert_eq!(local.strftime("%S"), "30".to_string());
1449 assert_eq!(local.strftime("%s"), "1234567890".to_string());
1450 assert_eq!(local.strftime("%T"), "15:31:30".to_string());
1451 assert_eq!(local.strftime("%t"), "\t".to_string());
1452 assert_eq!(local.strftime("%U"), "06".to_string());
1453 assert_eq!(local.strftime("%u"), "5".to_string());
1454 assert_eq!(local.strftime("%V"), "07".to_string());
1455 assert_eq!(local.strftime("%v"), "13-Feb-2009".to_string());
1456 assert_eq!(local.strftime("%W"), "06".to_string());
1457 assert_eq!(local.strftime("%w"), "5".to_string());
1458 assert_eq!(local.strftime("%X"), "15:31:30".to_string()); // FIXME (#2350): support locale
1459 assert_eq!(local.strftime("%x"), "02/13/09".to_string()); // FIXME (#2350): support locale
1460 assert_eq!(local.strftime("%Y"), "2009".to_string());
1461 assert_eq!(local.strftime("%y"), "09".to_string());
1462 assert_eq!(local.strftime("%+"), "2009-02-13T15:31:30-08:00".to_string());
1463 assert_eq!(local.strftime("%z"), "-0800".to_string());
1464 assert_eq!(local.strftime("%%"), "%".to_string());
1466 assert_eq!(local.asctime(), "Fri Feb 13 15:31:30 2009".to_string());
1467 assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1468 assert_eq!(local.rfc822z(), "Fri, 13 Feb 2009 15:31:30 -0800".to_string());
1469 assert_eq!(local.rfc3339(), "2009-02-13T15:31:30-08:00".to_string());
1471 assert_eq!(utc.asctime(), "Fri Feb 13 23:31:30 2009".to_string());
1472 assert_eq!(utc.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1473 assert_eq!(utc.rfc822(), "Fri, 13 Feb 2009 23:31:30 GMT".to_string());
1474 assert_eq!(utc.rfc822z(), "Fri, 13 Feb 2009 23:31:30 -0000".to_string());
1475 assert_eq!(utc.rfc3339(), "2009-02-13T23:31:30Z".to_string());
1478 fn test_timespec_eq_ord() {
1479 let a = &Timespec::new(-2, 1);
1480 let b = &Timespec::new(-1, 2);
1481 let c = &Timespec::new(1, 2);
1482 let d = &Timespec::new(2, 1);
1483 let e = &Timespec::new(2, 1);
1510 #[ignore(cfg(target_os = "android"))] // FIXME #10958
1512 // The tests race on tzset. So instead of having many independent
1513 // tests, we will just call the functions now.
1515 test_precise_time();
1524 test_timespec_eq_ord();
1528 fn bench_precise_time_ns(b: &mut Bencher) {
1529 b.iter(|| precise_time_ns())