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"]
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/",
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 * Return a string of the current time in the form
320 * "Thu Jan 1 00:00:00 1970".
322 pub fn ctime(&self) -> String { self.strftime("%c") }
324 /// Formats the time according to the format string.
325 pub fn strftime(&self, format: &str) -> String {
326 strftime(format, self)
330 * Returns a time string formatted according to RFC 822.
332 * local: "Thu, 22 Mar 2012 07:53:18 PST"
333 * utc: "Thu, 22 Mar 2012 14:53:18 UTC"
335 pub fn rfc822(&self) -> String {
336 if self.tm_gmtoff == 0_i32 {
337 self.strftime("%a, %d %b %Y %T GMT")
339 self.strftime("%a, %d %b %Y %T %Z")
344 * Returns a time string formatted according to RFC 822 with Zulu time.
346 * local: "Thu, 22 Mar 2012 07:53:18 -0700"
347 * utc: "Thu, 22 Mar 2012 14:53:18 -0000"
349 pub fn rfc822z(&self) -> String {
350 self.strftime("%a, %d %b %Y %T %z")
354 * Returns a time string formatted according to ISO 8601.
356 * local: "2012-02-22T07:53:18-07:00"
357 * utc: "2012-02-22T14:53:18Z"
359 pub fn rfc3339(&self) -> String {
360 if self.tm_gmtoff == 0_i32 {
361 self.strftime("%Y-%m-%dT%H:%M:%SZ")
363 let s = self.strftime("%Y-%m-%dT%H:%M:%S");
364 let sign = if self.tm_gmtoff > 0_i32 { '+' } else { '-' };
365 let mut m = num::abs(self.tm_gmtoff) / 60_i32;
368 format!("{}{}{:02d}:{:02d}", s, sign, h as int, m as int)
373 /// Parses the time from the string according to the format string.
374 pub fn strptime(s: &str, format: &str) -> Result<Tm, String> {
375 fn match_str(s: &str, pos: uint, needle: &str) -> bool {
377 for ch in needle.bytes() {
378 if s.as_bytes()[i] != ch {
386 fn match_strs(ss: &str, pos: uint, strs: &[(String, i32)])
387 -> Option<(i32, uint)> {
389 let len = strs.len();
391 match strs[i] { // can't use let due to let-pattern bugs
392 (ref needle, value) => {
393 if match_str(ss, pos, needle.as_slice()) {
394 return Some((value, pos + needle.len()));
404 fn match_digits(ss: &str, pos: uint, digits: uint, ws: bool)
405 -> Option<(i32, uint)> {
408 let mut value = 0_i32;
415 let range = ss.char_range_at(pos);
420 value = value * 10_i32 + (range.ch as i32 - '0' as i32);
431 fn match_fractional_seconds(ss: &str, pos: uint) -> (i32, uint) {
433 let mut value = 0_i32;
434 let mut multiplier = NSEC_PER_SEC / 10;
441 let range = ss.char_range_at(pos);
446 // This will drop digits after the nanoseconds place
447 let digit = range.ch as i32 - '0' as i32;
448 value += digit * multiplier;
458 fn match_digits_in_range(ss: &str, pos: uint, digits: uint, ws: bool,
459 min: i32, max: i32) -> Option<(i32, uint)> {
460 match match_digits(ss, pos, digits, ws) {
461 Some((val, pos)) if val >= min && val <= max => {
468 fn parse_char(s: &str, pos: uint, c: char) -> Result<uint, String> {
469 let range = s.char_range_at(pos);
474 Err(format!("Expected {}, found {}",
476 str::from_char(range.ch)))
480 fn parse_type(s: &str, pos: uint, ch: char, tm: &mut Tm)
481 -> Result<uint, String> {
483 'A' => match match_strs(s, pos, [
484 ("Sunday".to_string(), 0_i32),
485 ("Monday".to_string(), 1_i32),
486 ("Tuesday".to_string(), 2_i32),
487 ("Wednesday".to_string(), 3_i32),
488 ("Thursday".to_string(), 4_i32),
489 ("Friday".to_string(), 5_i32),
490 ("Saturday".to_string(), 6_i32)
492 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
493 None => Err("Invalid day".to_string())
495 'a' => match match_strs(s, pos, [
496 ("Sun".to_string(), 0_i32),
497 ("Mon".to_string(), 1_i32),
498 ("Tue".to_string(), 2_i32),
499 ("Wed".to_string(), 3_i32),
500 ("Thu".to_string(), 4_i32),
501 ("Fri".to_string(), 5_i32),
502 ("Sat".to_string(), 6_i32)
504 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
505 None => Err("Invalid day".to_string())
507 'B' => match match_strs(s, pos, [
508 ("January".to_string(), 0_i32),
509 ("February".to_string(), 1_i32),
510 ("March".to_string(), 2_i32),
511 ("April".to_string(), 3_i32),
512 ("May".to_string(), 4_i32),
513 ("June".to_string(), 5_i32),
514 ("July".to_string(), 6_i32),
515 ("August".to_string(), 7_i32),
516 ("September".to_string(), 8_i32),
517 ("October".to_string(), 9_i32),
518 ("November".to_string(), 10_i32),
519 ("December".to_string(), 11_i32)
521 Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
522 None => Err("Invalid month".to_string())
524 'b' | 'h' => match match_strs(s, pos, [
525 ("Jan".to_string(), 0_i32),
526 ("Feb".to_string(), 1_i32),
527 ("Mar".to_string(), 2_i32),
528 ("Apr".to_string(), 3_i32),
529 ("May".to_string(), 4_i32),
530 ("Jun".to_string(), 5_i32),
531 ("Jul".to_string(), 6_i32),
532 ("Aug".to_string(), 7_i32),
533 ("Sep".to_string(), 8_i32),
534 ("Oct".to_string(), 9_i32),
535 ("Nov".to_string(), 10_i32),
536 ("Dec".to_string(), 11_i32)
538 Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
539 None => Err("Invalid month".to_string())
541 'C' => match match_digits_in_range(s, pos, 2u, false, 0_i32,
545 tm.tm_year += (v * 100_i32) - 1900_i32;
548 None => Err("Invalid year".to_string())
551 parse_type(s, pos, 'a', &mut *tm)
552 .and_then(|pos| parse_char(s, pos, ' '))
553 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
554 .and_then(|pos| parse_char(s, pos, ' '))
555 .and_then(|pos| parse_type(s, pos, 'e', &mut *tm))
556 .and_then(|pos| parse_char(s, pos, ' '))
557 .and_then(|pos| parse_type(s, pos, 'T', &mut *tm))
558 .and_then(|pos| parse_char(s, pos, ' '))
559 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
562 parse_type(s, pos, 'm', &mut *tm)
563 .and_then(|pos| parse_char(s, pos, '/'))
564 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
565 .and_then(|pos| parse_char(s, pos, '/'))
566 .and_then(|pos| parse_type(s, pos, 'y', &mut *tm))
568 'd' => match match_digits_in_range(s, pos, 2u, false, 1_i32,
570 Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
571 None => Err("Invalid day of the month".to_string())
573 'e' => match match_digits_in_range(s, pos, 2u, true, 1_i32,
575 Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
576 None => Err("Invalid day of the month".to_string())
579 let (val, pos) = match_fractional_seconds(s, pos);
584 parse_type(s, pos, 'Y', &mut *tm)
585 .and_then(|pos| parse_char(s, pos, '-'))
586 .and_then(|pos| parse_type(s, pos, 'm', &mut *tm))
587 .and_then(|pos| parse_char(s, pos, '-'))
588 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
591 match match_digits_in_range(s, pos, 2u, false, 0_i32, 23_i32) {
592 Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
593 None => Err("Invalid hour".to_string())
597 match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
600 tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
603 None => Err("Invalid hour".to_string())
607 match match_digits_in_range(s, pos, 3u, false, 1_i32, 366_i32) {
610 tm.tm_yday = v - 1_i32;
613 None => Err("Invalid day of year".to_string())
617 match match_digits_in_range(s, pos, 2u, true, 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, true, 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, 2u, false, 0_i32, 59_i32) {
634 Some(item) => { let (v, pos) = item; tm.tm_min = v; Ok(pos) }
635 None => Err("Invalid minute".to_string())
639 match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
642 tm.tm_mon = v - 1_i32;
645 None => Err("Invalid month".to_string())
648 'n' => parse_char(s, pos, '\n'),
649 'P' => match match_strs(s, pos,
650 [("am".to_string(), 0_i32), ("pm".to_string(), 12_i32)]) {
652 Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
653 None => Err("Invalid hour".to_string())
655 'p' => match match_strs(s, pos,
656 [("AM".to_string(), 0_i32), ("PM".to_string(), 12_i32)]) {
658 Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
659 None => Err("Invalid hour".to_string())
662 parse_type(s, pos, 'H', &mut *tm)
663 .and_then(|pos| parse_char(s, pos, ':'))
664 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
667 parse_type(s, pos, 'I', &mut *tm)
668 .and_then(|pos| parse_char(s, pos, ':'))
669 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
670 .and_then(|pos| parse_char(s, pos, ':'))
671 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
672 .and_then(|pos| parse_char(s, pos, ' '))
673 .and_then(|pos| parse_type(s, pos, 'p', &mut *tm))
676 match match_digits_in_range(s, pos, 2u, false, 0_i32, 60_i32) {
682 None => Err("Invalid second".to_string())
687 parse_type(s, pos, 'H', &mut *tm)
688 .and_then(|pos| parse_char(s, pos, ':'))
689 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
690 .and_then(|pos| parse_char(s, pos, ':'))
691 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
693 't' => parse_char(s, pos, '\t'),
695 match match_digits_in_range(s, pos, 1u, false, 1_i32, 7_i32) {
698 tm.tm_wday = if v == 7 { 0 } else { v };
701 None => Err("Invalid day of week".to_string())
705 parse_type(s, pos, 'e', &mut *tm)
706 .and_then(|pos| parse_char(s, pos, '-'))
707 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
708 .and_then(|pos| parse_char(s, pos, '-'))
709 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
713 match match_digits_in_range(s, pos, 1u, false, 0_i32, 6_i32) {
714 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
715 None => Err("Invalid day of week".to_string())
719 match match_digits(s, pos, 4u, false) {
722 tm.tm_year = v - 1900_i32;
725 None => Err("Invalid year".to_string())
729 match match_digits_in_range(s, pos, 2u, false, 0_i32, 99_i32) {
735 None => Err("Invalid year".to_string())
739 if match_str(s, pos, "UTC") || match_str(s, pos, "GMT") {
740 tm.tm_gmtoff = 0_i32;
743 // It's odd, but to maintain compatibility with c's
744 // strptime we ignore the timezone.
748 let range = s.char_range_at(pos);
750 if range.ch == ' ' { break; }
757 let range = s.char_range_at(pos);
759 if range.ch == '+' || range.ch == '-' {
760 match match_digits(s, range.next, 4u, false) {
764 tm.tm_gmtoff = 0_i32;
769 None => Err("Invalid zone offset".to_string())
772 Err("Invalid zone offset".to_string())
775 '%' => parse_char(s, pos, '%'),
777 Err(format!("unknown formatting type: {}", str::from_char(ch)))
782 let mut rdr = BufReader::new(format.as_bytes());
798 let mut result = Err("Invalid time".to_string());
801 let range = s.char_range_at(pos);
803 let next = range.next;
806 let c = match rdr.read(buf) {
807 Ok(..) => buf[0] as char,
812 let ch = match rdr.read(buf) {
813 Ok(..) => buf[0] as char,
816 match parse_type(s, pos, ch, &mut tm) {
817 Ok(next) => pos = next,
818 Err(e) => { result = Err(e); break; }
828 if pos == len && rdr.tell().unwrap() == format.len() as u64 {
838 tm_isdst: tm.tm_isdst,
839 tm_gmtoff: tm.tm_gmtoff,
845 /// Formats the time according to the format string.
846 pub fn strftime(format: &str, tm: &Tm) -> String {
847 fn days_in_year(year: int) -> i32 {
848 if (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) {
849 366 /* Days in a leap year */
851 365 /* Days in a non-leap year */
855 fn iso_week_days(yday: i32, wday: i32) -> int {
856 /* The number of days from the first day of the first ISO week of this
857 * year to the year day YDAY with week day WDAY.
858 * ISO weeks start on Monday. The first ISO week has the year's first
860 * YDAY may be as small as yday_minimum.
862 let yday: int = yday as int;
863 let wday: int = wday as int;
864 let iso_week_start_wday: int = 1; /* Monday */
865 let iso_week1_wday: int = 4; /* Thursday */
866 let yday_minimum: int = 366;
867 /* Add enough to the first operand of % to make it nonnegative. */
868 let big_enough_multiple_of_7: int = (yday_minimum / 7 + 2) * 7;
870 yday - (yday - wday + iso_week1_wday + big_enough_multiple_of_7) % 7
871 + iso_week1_wday - iso_week_start_wday
874 fn iso_week(ch:char, tm: &Tm) -> String {
875 let mut year: int = tm.tm_year as int + 1900;
876 let mut days: int = iso_week_days (tm.tm_yday, tm.tm_wday);
879 /* This ISO week belongs to the previous year. */
881 days = iso_week_days (tm.tm_yday + (days_in_year(year)), tm.tm_wday);
883 let d: int = iso_week_days (tm.tm_yday - (days_in_year(year)),
886 /* This ISO week belongs to the next year. */
893 'G' => format!("{}", year),
894 'g' => format!("{:02d}", (year % 100 + 100) % 100),
895 'V' => format!("{:02d}", days / 7 + 1),
900 fn parse_type(ch: char, tm: &Tm) -> String {
902 format!("strftime: can't understand this format {} ", ch)
905 'A' => match tm.tm_wday as int {
906 0 => "Sunday".to_string(),
907 1 => "Monday".to_string(),
908 2 => "Tuesday".to_string(),
909 3 => "Wednesday".to_string(),
910 4 => "Thursday".to_string(),
911 5 => "Friday".to_string(),
912 6 => "Saturday".to_string(),
915 'a' => match tm.tm_wday as int {
916 0 => "Sun".to_string(),
917 1 => "Mon".to_string(),
918 2 => "Tue".to_string(),
919 3 => "Wed".to_string(),
920 4 => "Thu".to_string(),
921 5 => "Fri".to_string(),
922 6 => "Sat".to_string(),
925 'B' => match tm.tm_mon as int {
926 0 => "January".to_string(),
927 1 => "February".to_string(),
928 2 => "March".to_string(),
929 3 => "April".to_string(),
930 4 => "May".to_string(),
931 5 => "June".to_string(),
932 6 => "July".to_string(),
933 7 => "August".to_string(),
934 8 => "September".to_string(),
935 9 => "October".to_string(),
936 10 => "November".to_string(),
937 11 => "December".to_string(),
940 'b' | 'h' => match tm.tm_mon as int {
941 0 => "Jan".to_string(),
942 1 => "Feb".to_string(),
943 2 => "Mar".to_string(),
944 3 => "Apr".to_string(),
945 4 => "May".to_string(),
946 5 => "Jun".to_string(),
947 6 => "Jul".to_string(),
948 7 => "Aug".to_string(),
949 8 => "Sep".to_string(),
950 9 => "Oct".to_string(),
951 10 => "Nov".to_string(),
952 11 => "Dec".to_string(),
955 'C' => format!("{:02d}", (tm.tm_year as int + 1900) / 100),
957 format!("{} {} {} {} {}",
970 'd' => format!("{:02d}", tm.tm_mday),
971 'e' => format!("{:2d}", tm.tm_mday),
972 'f' => format!("{:09d}", tm.tm_nsec),
979 'G' => iso_week('G', tm),
980 'g' => iso_week('g', tm),
981 'H' => format!("{:02d}", tm.tm_hour),
983 let mut h = tm.tm_hour;
985 if h > 12 { h -= 12 }
988 'j' => format!("{:03d}", tm.tm_yday + 1),
989 'k' => format!("{:2d}", tm.tm_hour),
991 let mut h = tm.tm_hour;
993 if h > 12 { h -= 12 }
996 'M' => format!("{:02d}", tm.tm_min),
997 'm' => format!("{:02d}", tm.tm_mon + 1),
998 'n' => "\n".to_string(),
999 'P' => if (tm.tm_hour as int) < 12 { "am".to_string() } else { "pm".to_string() },
1000 'p' => if (tm.tm_hour as int) < 12 { "AM".to_string() } else { "PM".to_string() },
1003 parse_type('H', tm),
1004 parse_type('M', tm))
1007 format!("{}:{}:{} {}",
1008 parse_type('I', tm),
1009 parse_type('M', tm),
1010 parse_type('S', tm),
1011 parse_type('p', tm))
1013 'S' => format!("{:02d}", tm.tm_sec),
1014 's' => format!("{}", tm.to_timespec().sec),
1017 parse_type('H', tm),
1018 parse_type('M', tm),
1019 parse_type('S', tm))
1021 't' => "\t".to_string(),
1022 'U' => format!("{:02d}", (tm.tm_yday - tm.tm_wday + 7) / 7),
1024 let i = tm.tm_wday as int;
1025 (if i == 0 { 7 } else { i }).to_str()
1027 'V' => iso_week('V', tm),
1030 parse_type('e', tm),
1031 parse_type('b', tm),
1032 parse_type('Y', tm))
1036 (tm.tm_yday - (tm.tm_wday - 1 + 7) % 7 + 7) / 7)
1038 'w' => (tm.tm_wday as int).to_str(),
1039 'Y' => (tm.tm_year as int + 1900).to_str(),
1040 'y' => format!("{:02d}", (tm.tm_year as int + 1900) % 100),
1041 'Z' => "".to_string(), // FIXME(pcwalton): Implement this.
1043 let sign = if tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
1044 let mut m = num::abs(tm.tm_gmtoff) / 60_i32;
1047 format!("{}{:02d}{:02d}", sign, h, m)
1049 '+' => tm.rfc3339(),
1050 '%' => "%".to_string(),
1055 let mut buf = Vec::new();
1057 let mut rdr = BufReader::new(format.as_bytes());
1060 let ch = match rdr.read(b) {
1066 rdr.read(b).unwrap();
1067 let s = parse_type(b[0] as char, tm);
1068 buf.push_all(s.as_bytes());
1070 ch => buf.push(ch as u8)
1074 str::from_utf8(buf.as_slice()).unwrap().to_string()
1080 use super::{Timespec, get_time, precise_time_ns, precise_time_s, tzset,
1081 at_utc, at, strptime};
1084 use std::result::{Err, Ok};
1085 use self::test::Bencher;
1088 fn set_time_zone() {
1090 // Windows crt doesn't see any environment variable set by
1091 // `SetEnvironmentVariable`, which `os::setenv` internally uses.
1092 // It is why we use `putenv` here.
1094 fn _putenv(envstring: *const libc::c_char) -> libc::c_int;
1098 // Windows does not understand "America/Los_Angeles".
1099 // PST+08 may look wrong, but not! "PST" indicates
1100 // the name of timezone. "+08" means UTC = local + 08.
1101 "TZ=PST+08".with_c_str(|env| {
1107 #[cfg(not(windows))]
1108 fn set_time_zone() {
1110 os::setenv("TZ", "America/Los_Angeles");
1114 fn test_get_time() {
1115 static SOME_RECENT_DATE: i64 = 1325376000i64; // 2012-01-01T00:00:00Z
1116 static SOME_FUTURE_DATE: i64 = 1577836800i64; // 2020-01-01T00:00:00Z
1118 let tv1 = get_time();
1119 debug!("tv1={:?} sec + {:?} nsec", tv1.sec as uint, tv1.nsec as uint);
1121 assert!(tv1.sec > SOME_RECENT_DATE);
1122 assert!(tv1.nsec < 1000000000i32);
1124 let tv2 = get_time();
1125 debug!("tv2={:?} sec + {:?} nsec", tv2.sec as uint, tv2.nsec as uint);
1127 assert!(tv2.sec >= tv1.sec);
1128 assert!(tv2.sec < SOME_FUTURE_DATE);
1129 assert!(tv2.nsec < 1000000000i32);
1130 if tv2.sec == tv1.sec {
1131 assert!(tv2.nsec >= tv1.nsec);
1135 fn test_precise_time() {
1136 let s0 = precise_time_s();
1137 debug!("s0={} sec", f64::to_str_digits(s0, 9u));
1140 let ns0 = precise_time_ns();
1141 let ns1 = precise_time_ns();
1142 debug!("ns0={:?} ns", ns0);
1143 debug!("ns1={:?} ns", ns1);
1144 assert!(ns1 >= ns0);
1146 let ns2 = precise_time_ns();
1147 debug!("ns2={:?} ns", ns2);
1148 assert!(ns2 >= ns1);
1154 let time = Timespec::new(1234567890, 54321);
1155 let utc = at_utc(time);
1157 assert_eq!(utc.tm_sec, 30_i32);
1158 assert_eq!(utc.tm_min, 31_i32);
1159 assert_eq!(utc.tm_hour, 23_i32);
1160 assert_eq!(utc.tm_mday, 13_i32);
1161 assert_eq!(utc.tm_mon, 1_i32);
1162 assert_eq!(utc.tm_year, 109_i32);
1163 assert_eq!(utc.tm_wday, 5_i32);
1164 assert_eq!(utc.tm_yday, 43_i32);
1165 assert_eq!(utc.tm_isdst, 0_i32);
1166 assert_eq!(utc.tm_gmtoff, 0_i32);
1167 assert_eq!(utc.tm_nsec, 54321_i32);
1173 let time = Timespec::new(1234567890, 54321);
1174 let local = at(time);
1176 debug!("time_at: {:?}", local);
1178 assert_eq!(local.tm_sec, 30_i32);
1179 assert_eq!(local.tm_min, 31_i32);
1180 assert_eq!(local.tm_hour, 15_i32);
1181 assert_eq!(local.tm_mday, 13_i32);
1182 assert_eq!(local.tm_mon, 1_i32);
1183 assert_eq!(local.tm_year, 109_i32);
1184 assert_eq!(local.tm_wday, 5_i32);
1185 assert_eq!(local.tm_yday, 43_i32);
1186 assert_eq!(local.tm_isdst, 0_i32);
1187 assert_eq!(local.tm_gmtoff, -28800_i32);
1188 assert_eq!(local.tm_nsec, 54321_i32);
1191 fn test_to_timespec() {
1194 let time = Timespec::new(1234567890, 54321);
1195 let utc = at_utc(time);
1197 assert_eq!(utc.to_timespec(), time);
1198 assert_eq!(utc.to_local().to_timespec(), time);
1201 fn test_conversions() {
1204 let time = Timespec::new(1234567890, 54321);
1205 let utc = at_utc(time);
1206 let local = at(time);
1208 assert!(local.to_local() == local);
1209 assert!(local.to_utc() == utc);
1210 assert!(local.to_utc().to_local() == local);
1211 assert!(utc.to_utc() == utc);
1212 assert!(utc.to_local() == local);
1213 assert!(utc.to_local().to_utc() == utc);
1216 fn test_strptime() {
1219 match strptime("", "") {
1221 assert!(tm.tm_sec == 0_i32);
1222 assert!(tm.tm_min == 0_i32);
1223 assert!(tm.tm_hour == 0_i32);
1224 assert!(tm.tm_mday == 0_i32);
1225 assert!(tm.tm_mon == 0_i32);
1226 assert!(tm.tm_year == 0_i32);
1227 assert!(tm.tm_wday == 0_i32);
1228 assert!(tm.tm_isdst == 0_i32);
1229 assert!(tm.tm_gmtoff == 0_i32);
1230 assert!(tm.tm_nsec == 0_i32);
1235 let format = "%a %b %e %T.%f %Y";
1236 assert_eq!(strptime("", format), Err("Invalid time".to_string()));
1237 assert!(strptime("Fri Feb 13 15:31:30", format)
1238 == Err("Invalid time".to_string()));
1240 match strptime("Fri Feb 13 15:31:30.01234 2009", format) {
1243 assert!(tm.tm_sec == 30_i32);
1244 assert!(tm.tm_min == 31_i32);
1245 assert!(tm.tm_hour == 15_i32);
1246 assert!(tm.tm_mday == 13_i32);
1247 assert!(tm.tm_mon == 1_i32);
1248 assert!(tm.tm_year == 109_i32);
1249 assert!(tm.tm_wday == 5_i32);
1250 assert!(tm.tm_yday == 0_i32);
1251 assert!(tm.tm_isdst == 0_i32);
1252 assert!(tm.tm_gmtoff == 0_i32);
1253 assert!(tm.tm_nsec == 12340000_i32);
1257 fn test(s: &str, format: &str) -> bool {
1258 match strptime(s, format) {
1259 Ok(ref tm) => tm.strftime(format) == s.to_string(),
1265 "Sunday".to_string(),
1266 "Monday".to_string(),
1267 "Tuesday".to_string(),
1268 "Wednesday".to_string(),
1269 "Thursday".to_string(),
1270 "Friday".to_string(),
1271 "Saturday".to_string()
1273 for day in days.iter() {
1274 assert!(test(day.as_slice(), "%A"));
1286 for day in days.iter() {
1287 assert!(test(day.as_slice(), "%a"));
1291 "January".to_string(),
1292 "February".to_string(),
1293 "March".to_string(),
1294 "April".to_string(),
1298 "August".to_string(),
1299 "September".to_string(),
1300 "October".to_string(),
1301 "November".to_string(),
1302 "December".to_string()
1304 for day in months.iter() {
1305 assert!(test(day.as_slice(), "%B"));
1322 for day in months.iter() {
1323 assert!(test(day.as_slice(), "%b"));
1326 assert!(test("19", "%C"));
1327 assert!(test("Fri Feb 13 23:31:30 2009", "%c"));
1328 assert!(test("02/13/09", "%D"));
1329 assert!(test("03", "%d"));
1330 assert!(test("13", "%d"));
1331 assert!(test(" 3", "%e"));
1332 assert!(test("13", "%e"));
1333 assert!(test("2009-02-13", "%F"));
1334 assert!(test("03", "%H"));
1335 assert!(test("13", "%H"));
1336 assert!(test("03", "%I")); // FIXME (#2350): flesh out
1337 assert!(test("11", "%I")); // FIXME (#2350): flesh out
1338 assert!(test("044", "%j"));
1339 assert!(test(" 3", "%k"));
1340 assert!(test("13", "%k"));
1341 assert!(test(" 1", "%l"));
1342 assert!(test("11", "%l"));
1343 assert!(test("03", "%M"));
1344 assert!(test("13", "%M"));
1345 assert!(test("\n", "%n"));
1346 assert!(test("am", "%P"));
1347 assert!(test("pm", "%P"));
1348 assert!(test("AM", "%p"));
1349 assert!(test("PM", "%p"));
1350 assert!(test("23:31", "%R"));
1351 assert!(test("11:31:30 AM", "%r"));
1352 assert!(test("11:31:30 PM", "%r"));
1353 assert!(test("03", "%S"));
1354 assert!(test("13", "%S"));
1355 assert!(test("15:31:30", "%T"));
1356 assert!(test("\t", "%t"));
1357 assert!(test("1", "%u"));
1358 assert!(test("7", "%u"));
1359 assert!(test("13-Feb-2009", "%v"));
1360 assert!(test("0", "%w"));
1361 assert!(test("6", "%w"));
1362 assert!(test("2009", "%Y"));
1363 assert!(test("09", "%y"));
1364 assert!(strptime("-0000", "%z").unwrap().tm_gmtoff ==
1366 assert!(strptime("-0800", "%z").unwrap().tm_gmtoff ==
1368 assert!(test("%", "%%"));
1371 assert_eq!(strptime("360", "%Y-%m-%d"), Err("Invalid year".to_string()))
1377 let time = Timespec::new(1234567890, 54321);
1378 let utc = at_utc(time);
1379 let local = at(time);
1381 debug!("test_ctime: {:?} {:?}", utc.ctime(), local.ctime());
1383 assert_eq!(utc.ctime(), "Fri Feb 13 23:31:30 2009".to_string());
1384 assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1387 fn test_strftime() {
1390 let time = Timespec::new(1234567890, 54321);
1391 let utc = at_utc(time);
1392 let local = at(time);
1394 assert_eq!(local.strftime(""), "".to_string());
1395 assert_eq!(local.strftime("%A"), "Friday".to_string());
1396 assert_eq!(local.strftime("%a"), "Fri".to_string());
1397 assert_eq!(local.strftime("%B"), "February".to_string());
1398 assert_eq!(local.strftime("%b"), "Feb".to_string());
1399 assert_eq!(local.strftime("%C"), "20".to_string());
1400 assert_eq!(local.strftime("%c"), "Fri Feb 13 15:31:30 2009".to_string());
1401 assert_eq!(local.strftime("%D"), "02/13/09".to_string());
1402 assert_eq!(local.strftime("%d"), "13".to_string());
1403 assert_eq!(local.strftime("%e"), "13".to_string());
1404 assert_eq!(local.strftime("%f"), "000054321".to_string());
1405 assert_eq!(local.strftime("%F"), "2009-02-13".to_string());
1406 assert_eq!(local.strftime("%G"), "2009".to_string());
1407 assert_eq!(local.strftime("%g"), "09".to_string());
1408 assert_eq!(local.strftime("%H"), "15".to_string());
1409 assert_eq!(local.strftime("%I"), "03".to_string());
1410 assert_eq!(local.strftime("%j"), "044".to_string());
1411 assert_eq!(local.strftime("%k"), "15".to_string());
1412 assert_eq!(local.strftime("%l"), " 3".to_string());
1413 assert_eq!(local.strftime("%M"), "31".to_string());
1414 assert_eq!(local.strftime("%m"), "02".to_string());
1415 assert_eq!(local.strftime("%n"), "\n".to_string());
1416 assert_eq!(local.strftime("%P"), "pm".to_string());
1417 assert_eq!(local.strftime("%p"), "PM".to_string());
1418 assert_eq!(local.strftime("%R"), "15:31".to_string());
1419 assert_eq!(local.strftime("%r"), "03:31:30 PM".to_string());
1420 assert_eq!(local.strftime("%S"), "30".to_string());
1421 assert_eq!(local.strftime("%s"), "1234567890".to_string());
1422 assert_eq!(local.strftime("%T"), "15:31:30".to_string());
1423 assert_eq!(local.strftime("%t"), "\t".to_string());
1424 assert_eq!(local.strftime("%U"), "06".to_string());
1425 assert_eq!(local.strftime("%u"), "5".to_string());
1426 assert_eq!(local.strftime("%V"), "07".to_string());
1427 assert_eq!(local.strftime("%v"), "13-Feb-2009".to_string());
1428 assert_eq!(local.strftime("%W"), "06".to_string());
1429 assert_eq!(local.strftime("%w"), "5".to_string());
1430 assert_eq!(local.strftime("%X"), "15:31:30".to_string()); // FIXME (#2350): support locale
1431 assert_eq!(local.strftime("%x"), "02/13/09".to_string()); // FIXME (#2350): support locale
1432 assert_eq!(local.strftime("%Y"), "2009".to_string());
1433 assert_eq!(local.strftime("%y"), "09".to_string());
1434 assert_eq!(local.strftime("%+"), "2009-02-13T15:31:30-08:00".to_string());
1435 assert_eq!(local.strftime("%z"), "-0800".to_string());
1436 assert_eq!(local.strftime("%%"), "%".to_string());
1438 assert_eq!(local.ctime(), "Fri Feb 13 15:31:30 2009".to_string());
1439 assert_eq!(local.rfc822z(), "Fri, 13 Feb 2009 15:31:30 -0800".to_string());
1440 assert_eq!(local.rfc3339(), "2009-02-13T15:31:30-08:00".to_string());
1442 assert_eq!(utc.ctime(), "Fri Feb 13 23:31:30 2009".to_string());
1443 assert_eq!(utc.rfc822(), "Fri, 13 Feb 2009 23:31:30 GMT".to_string());
1444 assert_eq!(utc.rfc822z(), "Fri, 13 Feb 2009 23:31:30 -0000".to_string());
1445 assert_eq!(utc.rfc3339(), "2009-02-13T23:31:30Z".to_string());
1448 fn test_timespec_eq_ord() {
1449 let a = &Timespec::new(-2, 1);
1450 let b = &Timespec::new(-1, 2);
1451 let c = &Timespec::new(1, 2);
1452 let d = &Timespec::new(2, 1);
1453 let e = &Timespec::new(2, 1);
1480 #[ignore(cfg(target_os = "android"))] // FIXME #10958
1482 // The tests race on tzset. So instead of having many independent
1483 // tests, we will just call the functions now.
1485 test_precise_time();
1493 test_timespec_eq_ord();
1497 fn bench_precise_time_ns(b: &mut Bencher) {
1498 b.iter(|| precise_time_ns())