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 #[allow(missing_doc)];
13 use std::io::BufReader;
18 static NSEC_PER_SEC: i32 = 1_000_000_000_i32;
25 pub fn rust_gmtime(sec: i64, nsec: i32, result: &mut Tm);
26 pub fn rust_localtime(sec: i64, nsec: i32, result: &mut Tm);
27 pub fn rust_timegm(tm: &Tm) -> i64;
28 pub fn rust_mktime(tm: &Tm) -> i64;
32 #[cfg(unix, not(target_os = "macos"))]
34 use std::libc::{c_int, timespec};
36 // Apparently android provides this in some other library?
37 #[cfg(not(target_os = "android"))]
42 pub fn clock_gettime(clk_id: c_int, tp: *mut timespec) -> c_int;
46 #[cfg(target_os = "macos")]
48 use std::libc::{timeval, timezone, c_int, mach_timebase_info};
51 pub fn gettimeofday(tp: *mut timeval, tzp: *mut timezone) -> c_int;
52 pub fn mach_absolute_time() -> u64;
53 pub fn mach_timebase_info(info: *mut mach_timebase_info) -> c_int;
57 /// A record specifying a time value in seconds and nanoseconds.
60 #[deriving(Clone, DeepClone, Eq, Encodable, Decodable)]
61 pub struct Timespec { sec: i64, nsec: i32 }
63 * Timespec assumes that pre-epoch Timespecs have negative sec and positive
64 * nsec fields. Darwin's and Linux's struct timespec functions handle pre-
65 * epoch timestamps using a "two steps back, one step forward" representation,
66 * though the man pages do not actually document this. For example, the time
67 * -1.2 seconds before the epoch is represented by `Timespec { sec: -2_i64,
68 * nsec: 800_000_000_i32 }`.
71 pub fn new(sec: i64, nsec: i32) -> Timespec {
72 assert!(nsec >= 0 && nsec < NSEC_PER_SEC);
73 Timespec { sec: sec, nsec: nsec }
77 impl Ord for Timespec {
78 fn lt(&self, other: &Timespec) -> bool {
79 self.sec < other.sec ||
80 (self.sec == other.sec && self.nsec < other.nsec)
85 * Returns the current time as a `timespec` containing the seconds and
86 * nanoseconds since 1970-01-01T00:00:00Z.
88 pub fn get_time() -> Timespec {
90 let (sec, nsec) = os_get_time();
91 return Timespec::new(sec, nsec);
95 unsafe fn os_get_time() -> (i64, i32) {
96 static NANOSECONDS_FROM_1601_TO_1970: u64 = 11644473600000000;
98 let mut time = libc::FILETIME {
102 libc::GetSystemTimeAsFileTime(&mut time);
104 // A FILETIME contains a 64-bit value representing the number of
105 // hectonanosecond (100-nanosecond) intervals since 1601-01-01T00:00:00Z.
106 // http://support.microsoft.com/kb/167296/en-us
107 let ns_since_1601 = ((time.dwHighDateTime as u64 << 32) |
108 (time.dwLowDateTime as u64 << 0)) / 10;
109 let ns_since_1970 = ns_since_1601 - NANOSECONDS_FROM_1601_TO_1970;
111 ((ns_since_1970 / 1000000) as i64,
112 ((ns_since_1970 % 1000000) * 1000) as i32)
115 #[cfg(target_os = "macos")]
116 unsafe fn os_get_time() -> (i64, i32) {
118 let mut tv = libc::timeval { tv_sec: 0, tv_usec: 0 };
119 imp::gettimeofday(&mut tv, ptr::mut_null());
120 (tv.tv_sec as i64, tv.tv_usec * 1000)
123 #[cfg(not(target_os = "macos"), not(windows))]
124 unsafe fn os_get_time() -> (i64, i32) {
125 let mut tv = libc::timespec { tv_sec: 0, tv_nsec: 0 };
126 imp::clock_gettime(libc::CLOCK_REALTIME, &mut tv);
127 (tv.tv_sec as i64, tv.tv_nsec as i32)
133 * Returns the current value of a high-resolution performance counter
134 * in nanoseconds since an unspecified epoch.
136 pub fn precise_time_ns() -> u64 {
137 return os_precise_time_ns();
140 fn os_precise_time_ns() -> u64 {
141 let mut ticks_per_s = 0;
143 libc::QueryPerformanceFrequency(&mut ticks_per_s)
145 let ticks_per_s = if ticks_per_s == 0 {1} else {ticks_per_s};
148 libc::QueryPerformanceCounter(&mut ticks)
151 return (ticks as u64 * 1000000000) / (ticks_per_s as u64);
154 #[cfg(target_os = "macos")]
155 fn os_precise_time_ns() -> u64 {
156 let time = unsafe { imp::mach_absolute_time() };
157 let mut info = libc::mach_timebase_info { numer: 0, denom: 0 };
158 unsafe { imp::mach_timebase_info(&mut info); }
159 return time * ((info.numer / info.denom) as u64);
162 #[cfg(not(windows), not(target_os = "macos"))]
163 fn os_precise_time_ns() -> u64 {
164 let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
166 imp::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts);
168 return (ts.tv_sec as u64) * 1000000000 + (ts.tv_nsec as u64)
174 * Returns the current value of a high-resolution performance counter
175 * in seconds since an unspecified epoch.
177 pub fn precise_time_s() -> f64 {
178 return (precise_time_ns() as f64) / 1000000000.;
183 rustrt::rust_tzset();
187 #[deriving(Clone, DeepClone, Eq, Encodable, Decodable)]
189 tm_sec: i32, // seconds after the minute ~[0-60]
190 tm_min: i32, // minutes after the hour ~[0-59]
191 tm_hour: i32, // hours after midnight ~[0-23]
192 tm_mday: i32, // days of the month ~[1-31]
193 tm_mon: i32, // months since January ~[0-11]
194 tm_year: i32, // years since 1900
195 tm_wday: i32, // days since Sunday ~[0-6]
196 tm_yday: i32, // days since January 1 ~[0-365]
197 tm_isdst: i32, // Daylight Savings Time flag
198 tm_gmtoff: i32, // offset from UTC in seconds
199 tm_zone: ~str, // timezone abbreviation
200 tm_nsec: i32, // nanoseconds
203 pub fn empty_tm() -> Tm {
204 // 64 is the max size of the timezone buffer allocated on windows
205 // in rust_localtime. In glibc the max timezone size is supposedly 3.
206 let zone = str::with_capacity(64);
223 /// Returns the specified time in UTC
224 pub fn at_utc(clock: Timespec) -> Tm {
226 let Timespec { sec, nsec } = clock;
227 let mut tm = empty_tm();
228 rustrt::rust_gmtime(sec, nsec, &mut tm);
233 /// Returns the current time in UTC
234 pub fn now_utc() -> Tm {
238 /// Returns the specified time in the local timezone
239 pub fn at(clock: Timespec) -> Tm {
241 let Timespec { sec, nsec } = clock;
242 let mut tm = empty_tm();
243 rustrt::rust_localtime(sec, nsec, &mut tm);
248 /// Returns the current time in the local timezone
255 /// Convert time to the seconds from January 1, 1970
256 pub fn to_timespec(&self) -> Timespec {
258 let sec = match self.tm_gmtoff {
259 0_i32 => rustrt::rust_timegm(self),
260 _ => rustrt::rust_mktime(self)
263 Timespec::new(sec, self.tm_nsec)
267 /// Convert time to the local timezone
268 pub fn to_local(&self) -> Tm {
269 at(self.to_timespec())
272 /// Convert time to the UTC
273 pub fn to_utc(&self) -> Tm {
274 at_utc(self.to_timespec())
278 * Return a string of the current time in the form
279 * "Thu Jan 1 00:00:00 1970".
281 pub fn ctime(&self) -> ~str { self.strftime("%c") }
283 /// Formats the time according to the format string.
284 pub fn strftime(&self, format: &str) -> ~str {
285 strftime(format, self)
289 * Returns a time string formatted according to RFC 822.
291 * local: "Thu, 22 Mar 2012 07:53:18 PST"
292 * utc: "Thu, 22 Mar 2012 14:53:18 UTC"
294 pub fn rfc822(&self) -> ~str {
295 if self.tm_gmtoff == 0_i32 {
296 self.strftime("%a, %d %b %Y %T GMT")
298 self.strftime("%a, %d %b %Y %T %Z")
303 * Returns a time string formatted according to RFC 822 with Zulu time.
305 * local: "Thu, 22 Mar 2012 07:53:18 -0700"
306 * utc: "Thu, 22 Mar 2012 14:53:18 -0000"
308 pub fn rfc822z(&self) -> ~str {
309 self.strftime("%a, %d %b %Y %T %z")
313 * Returns a time string formatted according to ISO 8601.
315 * local: "2012-02-22T07:53:18-07:00"
316 * utc: "2012-02-22T14:53:18Z"
318 pub fn rfc3339(&self) -> ~str {
319 if self.tm_gmtoff == 0_i32 {
320 self.strftime("%Y-%m-%dT%H:%M:%SZ")
322 let s = self.strftime("%Y-%m-%dT%H:%M:%S");
323 let sign = if self.tm_gmtoff > 0_i32 { '+' } else { '-' };
324 let mut m = num::abs(self.tm_gmtoff) / 60_i32;
327 s + format!("{}{:02d}:{:02d}", sign, h as int, m as int)
332 /// Parses the time from the string according to the format string.
333 pub fn strptime(s: &str, format: &str) -> Result<Tm, ~str> {
334 fn match_str(s: &str, pos: uint, needle: &str) -> bool {
336 for ch in needle.bytes() {
345 fn match_strs(ss: &str, pos: uint, strs: &[(~str, i32)])
346 -> Option<(i32, uint)> {
348 let len = strs.len();
350 match strs[i] { // can't use let due to let-pattern bugs
351 (ref needle, value) => {
352 if match_str(ss, pos, *needle) {
353 return Some((value, pos + needle.len()));
363 fn match_digits(ss: &str, pos: uint, digits: uint, ws: bool)
364 -> Option<(i32, uint)> {
367 let mut value = 0_i32;
374 let range = ss.char_range_at(pos);
379 value = value * 10_i32 + (range.ch as i32 - '0' as i32);
390 fn match_fractional_seconds(ss: &str, pos: uint) -> (i32, uint) {
392 let mut value = 0_i32;
393 let mut multiplier = NSEC_PER_SEC / 10;
400 let range = ss.char_range_at(pos);
405 // This will drop digits after the nanoseconds place
406 let digit = range.ch as i32 - '0' as i32;
407 value += digit * multiplier;
417 fn match_digits_in_range(ss: &str, pos: uint, digits: uint, ws: bool,
418 min: i32, max: i32) -> Option<(i32, uint)> {
419 match match_digits(ss, pos, digits, ws) {
420 Some((val, pos)) if val >= min && val <= max => {
427 fn parse_char(s: &str, pos: uint, c: char) -> Result<uint, ~str> {
428 let range = s.char_range_at(pos);
433 Err(format!("Expected {}, found {}",
435 str::from_char(range.ch)))
439 fn parse_type(s: &str, pos: uint, ch: char, tm: &mut Tm)
440 -> Result<uint, ~str> {
442 'A' => match match_strs(s, pos, [
446 (~"Wednesday", 3_i32),
447 (~"Thursday", 4_i32),
451 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
452 None => Err(~"Invalid day")
454 'a' => match match_strs(s, pos, [
463 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
464 None => Err(~"Invalid day")
466 'B' => match match_strs(s, pos, [
468 (~"February", 1_i32),
475 (~"September", 8_i32),
477 (~"November", 10_i32),
478 (~"December", 11_i32)
480 Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
481 None => Err(~"Invalid month")
483 'b' | 'h' => match match_strs(s, pos, [
497 Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
498 None => Err(~"Invalid month")
500 'C' => match match_digits_in_range(s, pos, 2u, false, 0_i32,
504 tm.tm_year += (v * 100_i32) - 1900_i32;
507 None => Err(~"Invalid year")
510 parse_type(s, pos, 'a', &mut *tm)
511 .and_then(|pos| parse_char(s, pos, ' '))
512 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
513 .and_then(|pos| parse_char(s, pos, ' '))
514 .and_then(|pos| parse_type(s, pos, 'e', &mut *tm))
515 .and_then(|pos| parse_char(s, pos, ' '))
516 .and_then(|pos| parse_type(s, pos, 'T', &mut *tm))
517 .and_then(|pos| parse_char(s, pos, ' '))
518 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
521 parse_type(s, pos, 'm', &mut *tm)
522 .and_then(|pos| parse_char(s, pos, '/'))
523 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
524 .and_then(|pos| parse_char(s, pos, '/'))
525 .and_then(|pos| parse_type(s, pos, 'y', &mut *tm))
527 'd' => match match_digits_in_range(s, pos, 2u, false, 1_i32,
529 Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
530 None => Err(~"Invalid day of the month")
532 'e' => match match_digits_in_range(s, pos, 2u, true, 1_i32,
534 Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
535 None => Err(~"Invalid day of the month")
538 let (val, pos) = match_fractional_seconds(s, pos);
543 parse_type(s, pos, 'Y', &mut *tm)
544 .and_then(|pos| parse_char(s, pos, '-'))
545 .and_then(|pos| parse_type(s, pos, 'm', &mut *tm))
546 .and_then(|pos| parse_char(s, pos, '-'))
547 .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
550 match match_digits_in_range(s, pos, 2u, false, 0_i32, 23_i32) {
551 Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
552 None => Err(~"Invalid hour")
556 match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
559 tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
562 None => Err(~"Invalid hour")
566 match match_digits_in_range(s, pos, 3u, false, 1_i32, 366_i32) {
569 tm.tm_yday = v - 1_i32;
572 None => Err(~"Invalid day of year")
576 match match_digits_in_range(s, pos, 2u, true, 0_i32, 23_i32) {
577 Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
578 None => Err(~"Invalid hour")
582 match match_digits_in_range(s, pos, 2u, true, 1_i32, 12_i32) {
585 tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
588 None => Err(~"Invalid hour")
592 match match_digits_in_range(s, pos, 2u, false, 0_i32, 59_i32) {
593 Some(item) => { let (v, pos) = item; tm.tm_min = v; Ok(pos) }
594 None => Err(~"Invalid minute")
598 match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
601 tm.tm_mon = v - 1_i32;
604 None => Err(~"Invalid month")
607 'n' => parse_char(s, pos, '\n'),
608 'P' => match match_strs(s, pos,
609 [(~"am", 0_i32), (~"pm", 12_i32)]) {
611 Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
612 None => Err(~"Invalid hour")
614 'p' => match match_strs(s, pos,
615 [(~"AM", 0_i32), (~"PM", 12_i32)]) {
617 Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
618 None => Err(~"Invalid hour")
621 parse_type(s, pos, 'H', &mut *tm)
622 .and_then(|pos| parse_char(s, pos, ':'))
623 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
626 parse_type(s, pos, 'I', &mut *tm)
627 .and_then(|pos| parse_char(s, pos, ':'))
628 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
629 .and_then(|pos| parse_char(s, pos, ':'))
630 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
631 .and_then(|pos| parse_char(s, pos, ' '))
632 .and_then(|pos| parse_type(s, pos, 'p', &mut *tm))
635 match match_digits_in_range(s, pos, 2u, false, 0_i32, 60_i32) {
641 None => Err(~"Invalid second")
646 parse_type(s, pos, 'H', &mut *tm)
647 .and_then(|pos| parse_char(s, pos, ':'))
648 .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
649 .and_then(|pos| parse_char(s, pos, ':'))
650 .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
652 't' => parse_char(s, pos, '\t'),
654 match match_digits_in_range(s, pos, 1u, false, 1_i32, 7_i32) {
657 tm.tm_wday = if v == 7 { 0 } else { v };
660 None => Err(~"Invalid day of week")
664 parse_type(s, pos, 'e', &mut *tm)
665 .and_then(|pos| parse_char(s, pos, '-'))
666 .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
667 .and_then(|pos| parse_char(s, pos, '-'))
668 .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
672 match match_digits_in_range(s, pos, 1u, false, 0_i32, 6_i32) {
673 Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
674 None => Err(~"Invalid day of week")
678 match match_digits(s, pos, 4u, false) {
681 tm.tm_year = v - 1900_i32;
684 None => Err(~"Invalid year")
688 match match_digits_in_range(s, pos, 2u, false, 0_i32, 99_i32) {
694 None => Err(~"Invalid year")
698 if match_str(s, pos, "UTC") || match_str(s, pos, "GMT") {
699 tm.tm_gmtoff = 0_i32;
703 // It's odd, but to maintain compatibility with c's
704 // strptime we ignore the timezone.
708 let range = s.char_range_at(pos);
710 if range.ch == ' ' { break; }
717 let range = s.char_range_at(pos);
719 if range.ch == '+' || range.ch == '-' {
720 match match_digits(s, range.next, 4u, false) {
724 tm.tm_gmtoff = 0_i32;
730 None => Err(~"Invalid zone offset")
733 Err(~"Invalid zone offset")
736 '%' => parse_char(s, pos, '%'),
738 Err(format!("unknown formatting type: {}", str::from_char(ch)))
743 let mut rdr = BufReader::new(format.as_bytes());
760 let mut result = Err(~"Invalid time");
763 let range = s.char_range_at(pos);
765 let next = range.next;
768 let c = match rdr.read(buf) {
769 Some(..) => buf[0] as char,
774 let ch = match rdr.read(buf) {
775 Some(..) => buf[0] as char,
778 match parse_type(s, pos, ch, &mut tm) {
779 Ok(next) => pos = next,
780 Err(e) => { result = Err(e); break; }
790 if pos == len && rdr.tell() as uint == format.len() {
800 tm_isdst: tm.tm_isdst,
801 tm_gmtoff: tm.tm_gmtoff,
802 tm_zone: tm.tm_zone.clone(),
808 /// Formats the time according to the format string.
809 pub fn strftime(format: &str, tm: &Tm) -> ~str {
810 fn days_in_year(year: int) -> i32 {
811 if ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))) {
812 366 /* Days in a leap year */
814 365 /* Days in a non-leap year */
818 fn iso_week_days(yday: i32, wday: i32) -> int {
819 /* The number of days from the first day of the first ISO week of this
820 * year to the year day YDAY with week day WDAY.
821 * ISO weeks start on Monday. The first ISO week has the year's first
823 * YDAY may be as small as yday_minimum.
825 let yday: int = yday as int;
826 let wday: int = wday as int;
827 let iso_week_start_wday: int = 1; /* Monday */
828 let iso_week1_wday: int = 4; /* Thursday */
829 let yday_minimum: int = 366;
830 /* Add enough to the first operand of % to make it nonnegative. */
831 let big_enough_multiple_of_7: int = (yday_minimum / 7 + 2) * 7;
833 yday - (yday - wday + iso_week1_wday + big_enough_multiple_of_7) % 7
834 + iso_week1_wday - iso_week_start_wday
837 fn iso_week(ch:char, tm: &Tm) -> ~str {
838 let mut year: int = tm.tm_year as int + 1900;
839 let mut days: int = iso_week_days (tm.tm_yday, tm.tm_wday);
842 /* This ISO week belongs to the previous year. */
844 days = iso_week_days (tm.tm_yday + (days_in_year(year)), tm.tm_wday);
846 let d: int = iso_week_days (tm.tm_yday - (days_in_year(year)),
849 /* This ISO week belongs to the next year. */
856 'G' => format!("{}", year),
857 'g' => format!("{:02d}", (year % 100 + 100) % 100),
858 'V' => format!("{:02d}", days / 7 + 1),
863 fn parse_type(ch: char, tm: &Tm) -> ~str {
864 let die = || format!("strftime: can't understand this format {} ", ch);
866 'A' => match tm.tm_wday as int {
876 'a' => match tm.tm_wday as int {
886 'B' => match tm.tm_mon as int {
901 'b' | 'h' => match tm.tm_mon as int {
916 'C' => format!("{:02d}", (tm.tm_year as int + 1900) / 100),
918 format!("{} {} {} {} {}",
931 'd' => format!("{:02d}", tm.tm_mday),
932 'e' => format!("{:2d}", tm.tm_mday),
933 'f' => format!("{:09d}", tm.tm_nsec),
940 'G' => iso_week('G', tm),
941 'g' => iso_week('g', tm),
942 'H' => format!("{:02d}", tm.tm_hour),
944 let mut h = tm.tm_hour;
946 if h > 12 { h -= 12 }
949 'j' => format!("{:03d}", tm.tm_yday + 1),
950 'k' => format!("{:2d}", tm.tm_hour),
952 let mut h = tm.tm_hour;
954 if h > 12 { h -= 12 }
957 'M' => format!("{:02d}", tm.tm_min),
958 'm' => format!("{:02d}", tm.tm_mon + 1),
960 'P' => if (tm.tm_hour as int) < 12 { ~"am" } else { ~"pm" },
961 'p' => if (tm.tm_hour as int) < 12 { ~"AM" } else { ~"PM" },
968 format!("{}:{}:{} {}",
974 'S' => format!("{:02d}", tm.tm_sec),
975 's' => format!("{}", tm.to_timespec().sec),
983 'U' => format!("{:02d}", (tm.tm_yday - tm.tm_wday + 7) / 7),
985 let i = tm.tm_wday as int;
986 (if i == 0 { 7 } else { i }).to_str()
988 'V' => iso_week('V', tm),
995 'W' => format!("{:02d}", (tm.tm_yday - (tm.tm_wday - 1 + 7) % 7 + 7)
997 'w' => (tm.tm_wday as int).to_str(),
998 'Y' => (tm.tm_year as int + 1900).to_str(),
999 'y' => format!("{:02d}", (tm.tm_year as int + 1900) % 100),
1000 'Z' => tm.tm_zone.clone(),
1002 let sign = if tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
1003 let mut m = num::abs(tm.tm_gmtoff) / 60_i32;
1006 format!("{}{:02d}{:02d}", sign, h, m)
1008 '+' => tm.rfc3339(),
1016 let mut rdr = BufReader::new(format.as_bytes());
1019 let ch = match rdr.read(b) {
1026 let s = parse_type(b[0] as char, tm);
1027 buf.push_all(s.as_bytes());
1029 ch => buf.push(ch as u8)
1033 str::from_utf8_owned(buf)
1041 use std::result::{Err, Ok};
1044 fn set_time_zone() {
1046 // Windows crt doesn't see any environment variable set by
1047 // `SetEnvironmentVariable`, which `os::setenv` internally uses.
1048 // It is why we use `putenv` here.
1050 fn _putenv(envstring: *libc::c_char) -> libc::c_int;
1054 // Windows does not understand "America/Los_Angeles".
1055 // PST+08 may look wrong, but not! "PST" indicates
1056 // the name of timezone. "+08" means UTC = local + 08.
1057 "TZ=PST+08".with_c_str(|env| {
1063 #[cfg(not(windows))]
1064 fn set_time_zone() {
1066 os::setenv("TZ", "America/Los_Angeles");
1070 fn test_get_time() {
1071 static SOME_RECENT_DATE: i64 = 1325376000i64; // 2012-01-01T00:00:00Z
1072 static SOME_FUTURE_DATE: i64 = 1577836800i64; // 2020-01-01T00:00:00Z
1074 let tv1 = get_time();
1075 debug!("tv1={:?} sec + {:?} nsec", tv1.sec as uint, tv1.nsec as uint);
1077 assert!(tv1.sec > SOME_RECENT_DATE);
1078 assert!(tv1.nsec < 1000000000i32);
1080 let tv2 = get_time();
1081 debug!("tv2={:?} sec + {:?} nsec", tv2.sec as uint, tv2.nsec as uint);
1083 assert!(tv2.sec >= tv1.sec);
1084 assert!(tv2.sec < SOME_FUTURE_DATE);
1085 assert!(tv2.nsec < 1000000000i32);
1086 if tv2.sec == tv1.sec {
1087 assert!(tv2.nsec >= tv1.nsec);
1091 fn test_precise_time() {
1092 let s0 = precise_time_s();
1093 debug!("s0={} sec", f64::to_str_digits(s0, 9u));
1096 let ns0 = precise_time_ns();
1097 let ns1 = precise_time_ns();
1098 debug!("ns0={:?} ns", ns0);
1099 debug!("ns1={:?} ns", ns1);
1100 assert!(ns1 >= ns0);
1102 let ns2 = precise_time_ns();
1103 debug!("ns2={:?} ns", ns2);
1104 assert!(ns2 >= ns1);
1110 let time = Timespec::new(1234567890, 54321);
1111 let utc = at_utc(time);
1113 assert_eq!(utc.tm_sec, 30_i32);
1114 assert_eq!(utc.tm_min, 31_i32);
1115 assert_eq!(utc.tm_hour, 23_i32);
1116 assert_eq!(utc.tm_mday, 13_i32);
1117 assert_eq!(utc.tm_mon, 1_i32);
1118 assert_eq!(utc.tm_year, 109_i32);
1119 assert_eq!(utc.tm_wday, 5_i32);
1120 assert_eq!(utc.tm_yday, 43_i32);
1121 assert_eq!(utc.tm_isdst, 0_i32);
1122 assert_eq!(utc.tm_gmtoff, 0_i32);
1123 assert_eq!(utc.tm_zone, ~"UTC");
1124 assert_eq!(utc.tm_nsec, 54321_i32);
1130 let time = Timespec::new(1234567890, 54321);
1131 let local = at(time);
1133 error!("time_at: {:?}", local);
1135 assert_eq!(local.tm_sec, 30_i32);
1136 assert_eq!(local.tm_min, 31_i32);
1137 assert_eq!(local.tm_hour, 15_i32);
1138 assert_eq!(local.tm_mday, 13_i32);
1139 assert_eq!(local.tm_mon, 1_i32);
1140 assert_eq!(local.tm_year, 109_i32);
1141 assert_eq!(local.tm_wday, 5_i32);
1142 assert_eq!(local.tm_yday, 43_i32);
1143 assert_eq!(local.tm_isdst, 0_i32);
1144 assert_eq!(local.tm_gmtoff, -28800_i32);
1146 // FIXME (#2350): We should probably standardize on the timezone
1148 let zone = &local.tm_zone;
1149 assert!(*zone == ~"PST" || *zone == ~"Pacific Standard Time");
1151 assert_eq!(local.tm_nsec, 54321_i32);
1154 fn test_to_timespec() {
1157 let time = Timespec::new(1234567890, 54321);
1158 let utc = at_utc(time);
1160 assert_eq!(utc.to_timespec(), time);
1161 assert_eq!(utc.to_local().to_timespec(), time);
1164 fn test_conversions() {
1167 let time = Timespec::new(1234567890, 54321);
1168 let utc = at_utc(time);
1169 let local = at(time);
1171 assert!(local.to_local() == local);
1172 assert!(local.to_utc() == utc);
1173 assert!(local.to_utc().to_local() == local);
1174 assert!(utc.to_utc() == utc);
1175 assert!(utc.to_local() == local);
1176 assert!(utc.to_local().to_utc() == utc);
1179 fn test_strptime() {
1182 match strptime("", "") {
1184 assert!(tm.tm_sec == 0_i32);
1185 assert!(tm.tm_min == 0_i32);
1186 assert!(tm.tm_hour == 0_i32);
1187 assert!(tm.tm_mday == 0_i32);
1188 assert!(tm.tm_mon == 0_i32);
1189 assert!(tm.tm_year == 0_i32);
1190 assert!(tm.tm_wday == 0_i32);
1191 assert!(tm.tm_isdst == 0_i32);
1192 assert!(tm.tm_gmtoff == 0_i32);
1193 assert!(tm.tm_zone == ~"");
1194 assert!(tm.tm_nsec == 0_i32);
1199 let format = "%a %b %e %T.%f %Y";
1200 assert_eq!(strptime("", format), Err(~"Invalid time"));
1201 assert!(strptime("Fri Feb 13 15:31:30", format)
1202 == Err(~"Invalid time"));
1204 match strptime("Fri Feb 13 15:31:30.01234 2009", format) {
1207 assert!(tm.tm_sec == 30_i32);
1208 assert!(tm.tm_min == 31_i32);
1209 assert!(tm.tm_hour == 15_i32);
1210 assert!(tm.tm_mday == 13_i32);
1211 assert!(tm.tm_mon == 1_i32);
1212 assert!(tm.tm_year == 109_i32);
1213 assert!(tm.tm_wday == 5_i32);
1214 assert!(tm.tm_yday == 0_i32);
1215 assert!(tm.tm_isdst == 0_i32);
1216 assert!(tm.tm_gmtoff == 0_i32);
1217 assert!(tm.tm_zone == ~"");
1218 assert!(tm.tm_nsec == 12340000_i32);
1222 fn test(s: &str, format: &str) -> bool {
1223 match strptime(s, format) {
1224 Ok(ref tm) => tm.strftime(format) == s.to_owned(),
1238 for day in days.iter() {
1239 assert!(test(*day, "%A"));
1251 for day in days.iter() {
1252 assert!(test(*day, "%a"));
1269 for day in months.iter() {
1270 assert!(test(*day, "%B"));
1287 for day in months.iter() {
1288 assert!(test(*day, "%b"));
1291 assert!(test("19", "%C"));
1292 assert!(test("Fri Feb 13 23:31:30 2009", "%c"));
1293 assert!(test("02/13/09", "%D"));
1294 assert!(test("03", "%d"));
1295 assert!(test("13", "%d"));
1296 assert!(test(" 3", "%e"));
1297 assert!(test("13", "%e"));
1298 assert!(test("2009-02-13", "%F"));
1299 assert!(test("03", "%H"));
1300 assert!(test("13", "%H"));
1301 assert!(test("03", "%I")); // FIXME (#2350): flesh out
1302 assert!(test("11", "%I")); // FIXME (#2350): flesh out
1303 assert!(test("044", "%j"));
1304 assert!(test(" 3", "%k"));
1305 assert!(test("13", "%k"));
1306 assert!(test(" 1", "%l"));
1307 assert!(test("11", "%l"));
1308 assert!(test("03", "%M"));
1309 assert!(test("13", "%M"));
1310 assert!(test("\n", "%n"));
1311 assert!(test("am", "%P"));
1312 assert!(test("pm", "%P"));
1313 assert!(test("AM", "%p"));
1314 assert!(test("PM", "%p"));
1315 assert!(test("23:31", "%R"));
1316 assert!(test("11:31:30 AM", "%r"));
1317 assert!(test("11:31:30 PM", "%r"));
1318 assert!(test("03", "%S"));
1319 assert!(test("13", "%S"));
1320 assert!(test("15:31:30", "%T"));
1321 assert!(test("\t", "%t"));
1322 assert!(test("1", "%u"));
1323 assert!(test("7", "%u"));
1324 assert!(test("13-Feb-2009", "%v"));
1325 assert!(test("0", "%w"));
1326 assert!(test("6", "%w"));
1327 assert!(test("2009", "%Y"));
1328 assert!(test("09", "%y"));
1329 assert!(strptime("UTC", "%Z").unwrap().tm_zone ==
1331 assert!(strptime("PST", "%Z").unwrap().tm_zone ==
1333 assert!(strptime("-0000", "%z").unwrap().tm_gmtoff ==
1335 assert!(strptime("-0800", "%z").unwrap().tm_gmtoff ==
1337 assert!(test("%", "%%"));
1340 assert_eq!(strptime("360", "%Y-%m-%d"), Err(~"Invalid year"))
1346 let time = Timespec::new(1234567890, 54321);
1347 let utc = at_utc(time);
1348 let local = at(time);
1350 error!("test_ctime: {:?} {:?}", utc.ctime(), local.ctime());
1352 assert_eq!(utc.ctime(), ~"Fri Feb 13 23:31:30 2009");
1353 assert_eq!(local.ctime(), ~"Fri Feb 13 15:31:30 2009");
1356 fn test_strftime() {
1359 let time = Timespec::new(1234567890, 54321);
1360 let utc = at_utc(time);
1361 let local = at(time);
1363 assert_eq!(local.strftime(""), ~"");
1364 assert_eq!(local.strftime("%A"), ~"Friday");
1365 assert_eq!(local.strftime("%a"), ~"Fri");
1366 assert_eq!(local.strftime("%B"), ~"February");
1367 assert_eq!(local.strftime("%b"), ~"Feb");
1368 assert_eq!(local.strftime("%C"), ~"20");
1369 assert_eq!(local.strftime("%c"), ~"Fri Feb 13 15:31:30 2009");
1370 assert_eq!(local.strftime("%D"), ~"02/13/09");
1371 assert_eq!(local.strftime("%d"), ~"13");
1372 assert_eq!(local.strftime("%e"), ~"13");
1373 assert_eq!(local.strftime("%f"), ~"000054321");
1374 assert_eq!(local.strftime("%F"), ~"2009-02-13");
1375 assert_eq!(local.strftime("%G"), ~"2009");
1376 assert_eq!(local.strftime("%g"), ~"09");
1377 assert_eq!(local.strftime("%H"), ~"15");
1378 assert_eq!(local.strftime("%I"), ~"03");
1379 assert_eq!(local.strftime("%j"), ~"044");
1380 assert_eq!(local.strftime("%k"), ~"15");
1381 assert_eq!(local.strftime("%l"), ~" 3");
1382 assert_eq!(local.strftime("%M"), ~"31");
1383 assert_eq!(local.strftime("%m"), ~"02");
1384 assert_eq!(local.strftime("%n"), ~"\n");
1385 assert_eq!(local.strftime("%P"), ~"pm");
1386 assert_eq!(local.strftime("%p"), ~"PM");
1387 assert_eq!(local.strftime("%R"), ~"15:31");
1388 assert_eq!(local.strftime("%r"), ~"03:31:30 PM");
1389 assert_eq!(local.strftime("%S"), ~"30");
1390 assert_eq!(local.strftime("%s"), ~"1234567890");
1391 assert_eq!(local.strftime("%T"), ~"15:31:30");
1392 assert_eq!(local.strftime("%t"), ~"\t");
1393 assert_eq!(local.strftime("%U"), ~"06");
1394 assert_eq!(local.strftime("%u"), ~"5");
1395 assert_eq!(local.strftime("%V"), ~"07");
1396 assert_eq!(local.strftime("%v"), ~"13-Feb-2009");
1397 assert_eq!(local.strftime("%W"), ~"06");
1398 assert_eq!(local.strftime("%w"), ~"5");
1399 assert_eq!(local.strftime("%X"), ~"15:31:30"); // FIXME (#2350): support locale
1400 assert_eq!(local.strftime("%x"), ~"02/13/09"); // FIXME (#2350): support locale
1401 assert_eq!(local.strftime("%Y"), ~"2009");
1402 assert_eq!(local.strftime("%y"), ~"09");
1403 assert_eq!(local.strftime("%+"), ~"2009-02-13T15:31:30-08:00");
1405 // FIXME (#2350): We should probably standardize on the timezone
1407 let zone = local.strftime("%Z");
1408 assert!(zone == ~"PST" || zone == ~"Pacific Standard Time");
1410 assert_eq!(local.strftime("%z"), ~"-0800");
1411 assert_eq!(local.strftime("%%"), ~"%");
1413 // FIXME (#2350): We should probably standardize on the timezone
1415 let rfc822 = local.rfc822();
1416 let prefix = ~"Fri, 13 Feb 2009 15:31:30 ";
1417 assert!(rfc822 == prefix + "PST" || rfc822 == prefix + "Pacific Standard Time");
1419 assert_eq!(local.ctime(), ~"Fri Feb 13 15:31:30 2009");
1420 assert_eq!(local.rfc822z(), ~"Fri, 13 Feb 2009 15:31:30 -0800");
1421 assert_eq!(local.rfc3339(), ~"2009-02-13T15:31:30-08:00");
1423 assert_eq!(utc.ctime(), ~"Fri Feb 13 23:31:30 2009");
1424 assert_eq!(utc.rfc822(), ~"Fri, 13 Feb 2009 23:31:30 GMT");
1425 assert_eq!(utc.rfc822z(), ~"Fri, 13 Feb 2009 23:31:30 -0000");
1426 assert_eq!(utc.rfc3339(), ~"2009-02-13T23:31:30Z");
1429 fn test_timespec_eq_ord() {
1430 let a = &Timespec::new(-2, 1);
1431 let b = &Timespec::new(-1, 2);
1432 let c = &Timespec::new(1, 2);
1433 let d = &Timespec::new(2, 1);
1434 let e = &Timespec::new(2, 1);
1461 #[ignore(cfg(target_os = "android"))] // FIXME #10958
1463 // The tests race on tzset. So instead of having many independent
1464 // tests, we will just call the functions now.
1466 test_precise_time();
1474 test_timespec_eq_ord();