Skip to main content

Time

Struct Time 

Source
pub struct Time {
    pub hour: u8,
    pub minute: u8,
    pub second: u8,
    pub millisecond: u16,
}
Expand description

A time of day with millisecond precision

Supports validation, 12-hour conversion, and arithmetic with Duration (with cross-midnight wrapping).

§Examples

use rstime::Time;

let t = Time::new(14, 5, 9, 37);
assert!(t.is_valid());
assert_eq!(t.hour, 14);
assert_eq!(t.minute, 5);
assert_eq!(t.second, 9);
assert_eq!(t.millisecond, 37);

Fields§

§hour: u8

Hour (0-23)

§minute: u8

Minute (0-59)

§second: u8

Second (0-59)

§millisecond: u16

Millisecond (0-999)

Implementations§

Source§

impl Time

Source

pub fn now() -> Self

Convenience method: current time from the system clock

Examples found in repository?
examples/test_clock.rs (line 16)
3fn main() {
4    println!("=== rstime 时钟测试 ===\n");
5
6    println!("1. 系统时钟 - 当前时间");
7    let clock = SystemClock;
8    let now = clock.now();
9    println!("   DateTime: {}", now);
10    println!("   Date:     {}", clock.today());
11    println!("   Time:     {}", clock.time_now());
12    println!();
13
14    println!("2. 便捷方法(无需实例化 Clock)");
15    let today = rstime::Date::today();
16    let time_now = rstime::Time::now();
17    let datetime_now = rstime::DateTime::now();
18    println!("   Date::today()     → {}", today);
19    println!("   Time::now()       → {}", time_now);
20    println!("   DateTime::now()   → {}", datetime_now);
21    println!();
22
23    println!("3. 单调时钟 - 性能计时");
24    let timer = MonotonicClock::start();
25    let mut _sum: u64 = 0;
26    for i in 0..1_000_000 {
27        _sum += i;
28    }
29    let elapsed = timer.elapsed();
30    println!("   累加 100 万次: {}ms ({} 纳秒)", elapsed.total_millis(), elapsed.nanos);
31    println!();
32
33    println!("4. 单调时钟 - 重置");
34    let mut timer = MonotonicClock::start();
35    std::thread::sleep(std::time::Duration::from_millis(10));
36    println!("   第一次: {}ms", timer.elapsed().total_millis());
37    timer.reset();
38    println!("   重置后: {}ms", timer.elapsed().total_millis());
39    println!();
40
41    println!("5. Duration 常量");
42    println!("   ZERO:   {}ms", Duration::ZERO.total_millis());
43    println!("   SECOND: {}ms", Duration::SECOND.total_millis());
44    println!("   MINUTE: {}ms", Duration::MINUTE.total_millis());
45    println!("   HOUR:   {}ms", Duration::HOUR.total_millis());
46    println!("   DAY:    {}ms", Duration::DAY.total_millis());
47    println!();
48
49    println!("✅ 时钟测试完成!");
50}
More examples
Hide additional examples
examples/demo.rs (line 57)
3fn main() {
4    println!("=== rstime 时间库使用示例 ===\n");
5
6    println!("1. 获取当前时间");
7    let now = DateTime::now();
8    println!("   现在: {}\n", now);
9
10    println!("2. 格式化输出");
11    let dt = DateTime::from_ymd_hms_milli(2026, 5, 10, 14, 5, 9, 37);
12    println!("   ISO 8601:  {}", dt.format("{YYYY}-{MM}-{DD}T{HH}:{mm}:{ss}"));
13    println!("   中文格式:  {}", dt.format("{YYYY}年{MM}月{DD}日 {HH}:{mm}:{ss}"));
14    println!("   12小时制:  {}", dt.format("{hh}:{mm}:{ss} {AMPM}"));
15    println!("   星期:      {}", dt.format("{WW}"));
16    println!("   毫秒:      {}", dt.format("{SSS}"));
17    println!();
18
19    println!("3. 日期计算");
20    let d1 = Date::new(2026, 1, 1);
21    let d2 = d1 + TimeDelta::new(365 * 86400, 0);
22    let diff = d2 - d1;
23    println!("   {} + 365 天 = {}", d1, d2);
24    println!("   相差 {} 天", diff.total_seconds() as i64 / 86400);
25    println!();
26
27    println!("4. 星期计算");
28    let dates = [Date::new(2026, 1, 1), Date::new(2026, 5, 10), Date::new(2026, 12, 25)];
29    for d in &dates {
30        println!("   {} = {}", d, d.weekday());
31    }
32    println!();
33
34    println!("5. 闰年判断");
35    for year in [2024, 2025, 2000, 1900] {
36        println!("   {}: {}", year, if Date::new(year, 1, 1).is_leap_year() { "闰年" } else { "平年" });
37    }
38    println!();
39
40    println!("6. Unix 时间戳");
41    let epoch = DateTime::from_unix(0);
42    println!("   epoch:     {}", epoch);
43    let ts = now.unix_timestamp();
44    println!("   当前时间戳: {}", ts);
45    let ts_ms = now.unix_timestamp_millis();
46    println!("   毫秒时间戳: {}", ts_ms);
47    println!();
48
49    println!("7. 时间加法(跨天回绕)");
50    let t = Time::from_hms(23, 30, 0);
51    println!("   {} + 2h = {}", t, t + Duration::from_secs(7200));
52    println!("   {} - 1h = {}", t, t - Duration::HOUR);
53    println!();
54
55    println!("8. 时钟功能");
56    let today = Date::today();
57    let time_now = Time::now();
58    println!("   今天: {}", today);
59    println!("   此刻: {}", time_now);
60    println!();
61
62    println!("9. 单调时钟(性能计时)");
63    let timer = MonotonicClock::start();
64    let _sum: u64 = (0..10_000_000).sum();
65    let elapsed = timer.elapsed();
66    println!("   累加 1000 万次耗时: {}ms", elapsed.total_millis());
67    println!();
68
69    println!("✅ 所有示例运行完成!");
70}
Source§

impl Time

Source

pub const MIDNIGHT: Time

Midnight (00:00:00.000)

Source

pub const NOON: Time

Noon (12:00:00.000)

Source

pub const MAX: Time

Maximum time (23:59:59.999)

Source

pub fn new(hour: u8, minute: u8, second: u8, millisecond: u16) -> Self

Create a new time with millisecond precision

Examples found in repository?
examples/test_format.rs (line 8)
3fn main() {
4    println!("=== rstime 格式化测试 ===\n");
5
6    let dt = DateTime::from_ymd_hms_milli(2026, 5, 10, 14, 5, 9, 37);
7    let d = Date::new(2026, 5, 10);
8    let t = Time::new(14, 5, 9, 37);
9
10    println!("DateTime 格式化:");
11    println!("  YYYY-MM-DD HH:mm:ss    → {}", dt.format("{YYYY}-{MM}-{DD} {HH}:{mm}:{ss}"));
12    println!("  YYYY/MM/DD             → {}", dt.format("{YYYY}/{MM}/{DD}"));
13    println!("  YY-M-D                  → {}", dt.format("{YY}-{M}-{D}"));
14    println!("  12h                     → {}", dt.format("{hh}:{mm} {AMPM}"));
15    println!("  12h lowercase           → {}", dt.format("{h}:{m} {ampm}"));
16    println!("  With millis             → {}", dt.format("{HH}:{mm}:{ss}.{SSS}"));
17    println!("  Weekday short           → {}", dt.format("{W}"));
18    println!("  Weekday full            → {}", dt.format("{WW}"));
19    println!("  Literal text            → {}", dt.format("Today is {YYYY}-{MM}-{DD}!"));
20    println!();
21
22    println!("Date 格式化:");
23    println!("  YYYY-MM-DD              → {}", d.format("{YYYY}-{MM}-{DD}"));
24    println!("  Chinese date            → {}", d.format("{YYYY}年{MM}月{DD}日"));
25    println!("  Year only               → {}", d.format("{YYYY}"));
26    println!();
27
28    println!("Time 格式化:");
29    println!("  HH:mm:ss                → {}", t.format("{HH}:{mm}:{ss}"));
30    println!("  12h with AM/PM          → {}", t.format("{hh}:{mm} {AMPM}"));
31    println!("  With millis             → {}", t.format("{HH}:{mm}:{ss}.{SSS}"));
32    println!();
33
34    println!("预置格式:");
35    println!("  ISO8601:      {}", dt.format("{YYYY}-{MM}-{DD}T{HH}:{mm}:{ss}"));
36    println!("  RFC2822-ish:  {}", dt.format("{W}, {DD} {MM} {YYYY} {HH}:{mm}:{ss}"));
37    println!();
38
39    println!("边界值测试:");
40    let midnight = Time::MIDNIGHT;
41    let noon = Time::NOON;
42    let max = Time::MAX;
43    println!("  Midnight  → {}", midnight.format("{HH}:{mm}:{ss} {AMPM}"));
44    println!("  Noon      → {}", noon.format("{HH}:{mm}:{ss} {AMPM}"));
45    println!("  Max       → {}", max.format("{HH}:{mm}:{ss}.{SSS}"));
46    println!();
47
48    println!("✅ 格式化测试完成!");
49}
Source

pub fn from_hms(hour: u8, minute: u8, second: u8) -> Self

Create a time from hours, minutes, and seconds (no milliseconds)

Examples found in repository?
examples/demo.rs (line 50)
3fn main() {
4    println!("=== rstime 时间库使用示例 ===\n");
5
6    println!("1. 获取当前时间");
7    let now = DateTime::now();
8    println!("   现在: {}\n", now);
9
10    println!("2. 格式化输出");
11    let dt = DateTime::from_ymd_hms_milli(2026, 5, 10, 14, 5, 9, 37);
12    println!("   ISO 8601:  {}", dt.format("{YYYY}-{MM}-{DD}T{HH}:{mm}:{ss}"));
13    println!("   中文格式:  {}", dt.format("{YYYY}年{MM}月{DD}日 {HH}:{mm}:{ss}"));
14    println!("   12小时制:  {}", dt.format("{hh}:{mm}:{ss} {AMPM}"));
15    println!("   星期:      {}", dt.format("{WW}"));
16    println!("   毫秒:      {}", dt.format("{SSS}"));
17    println!();
18
19    println!("3. 日期计算");
20    let d1 = Date::new(2026, 1, 1);
21    let d2 = d1 + TimeDelta::new(365 * 86400, 0);
22    let diff = d2 - d1;
23    println!("   {} + 365 天 = {}", d1, d2);
24    println!("   相差 {} 天", diff.total_seconds() as i64 / 86400);
25    println!();
26
27    println!("4. 星期计算");
28    let dates = [Date::new(2026, 1, 1), Date::new(2026, 5, 10), Date::new(2026, 12, 25)];
29    for d in &dates {
30        println!("   {} = {}", d, d.weekday());
31    }
32    println!();
33
34    println!("5. 闰年判断");
35    for year in [2024, 2025, 2000, 1900] {
36        println!("   {}: {}", year, if Date::new(year, 1, 1).is_leap_year() { "闰年" } else { "平年" });
37    }
38    println!();
39
40    println!("6. Unix 时间戳");
41    let epoch = DateTime::from_unix(0);
42    println!("   epoch:     {}", epoch);
43    let ts = now.unix_timestamp();
44    println!("   当前时间戳: {}", ts);
45    let ts_ms = now.unix_timestamp_millis();
46    println!("   毫秒时间戳: {}", ts_ms);
47    println!();
48
49    println!("7. 时间加法(跨天回绕)");
50    let t = Time::from_hms(23, 30, 0);
51    println!("   {} + 2h = {}", t, t + Duration::from_secs(7200));
52    println!("   {} - 1h = {}", t, t - Duration::HOUR);
53    println!();
54
55    println!("8. 时钟功能");
56    let today = Date::today();
57    let time_now = Time::now();
58    println!("   今天: {}", today);
59    println!("   此刻: {}", time_now);
60    println!();
61
62    println!("9. 单调时钟(性能计时)");
63    let timer = MonotonicClock::start();
64    let _sum: u64 = (0..10_000_000).sum();
65    let elapsed = timer.elapsed();
66    println!("   累加 1000 万次耗时: {}ms", elapsed.total_millis());
67    println!();
68
69    println!("✅ 所有示例运行完成!");
70}
Source

pub fn is_valid(&self) -> bool

Check if the time is valid

use rstime::Time;

assert!(Time::new(14, 5, 9, 0).is_valid());
assert!(!Time::new(24, 0, 0, 0).is_valid());
assert!(!Time::new(0, 60, 0, 0).is_valid());
Source

pub fn total_seconds(&self) -> u32

Total time in seconds (since midnight)

Source

pub fn total_millis(&self) -> u32

Total time in milliseconds (since midnight)

Source

pub fn hour12(&self) -> (u8, bool)

Convert to 12-hour clock representation

Returns (hour, is_pm) where hour is 1-12.

use rstime::Time;

let t = Time::from_hms(14, 0, 0);
assert_eq!(t.hour12(), (2, true));

let midnight = Time::MIDNIGHT;
assert_eq!(midnight.hour12(), (12, false));
Source

pub fn is_pm(&self) -> bool

Returns true if the time is PM (hour >= 12)

Trait Implementations§

Source§

impl Add<Duration> for Time

Source§

fn add(self, delta: Duration) -> Time

Add a duration, wrapping around midnight

use rstime::{Time, Duration};

let t = Time::from_hms(23, 0, 0);
let t2 = t + Duration::HOUR * 2;
Source§

type Output = Time

The resulting type after applying the + operator.
Source§

impl Clone for Time

Source§

fn clone(&self) -> Time

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Time

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Time

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Hash for Time

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for Time

Source§

fn cmp(&self, other: &Time) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for Time

Source§

fn eq(&self, other: &Time) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for Time

Source§

fn partial_cmp(&self, other: &Time) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Sub<Duration> for Time

Source§

fn sub(self, delta: Duration) -> Time

Subtract a duration, wrapping around midnight

Source§

type Output = Time

The resulting type after applying the - operator.
Source§

impl Sub for Time

Source§

fn sub(self, rhs: Time) -> Duration

Calculate the difference between two times

Source§

type Output = Duration

The resulting type after applying the - operator.
Source§

impl TimeFormat for Time

Source§

fn format(&self, fmt: &str) -> String

Format the value using the given format string
Source§

impl Copy for Time

Source§

impl Eq for Time

Source§

impl StructuralPartialEq for Time

Auto Trait Implementations§

§

impl Freeze for Time

§

impl RefUnwindSafe for Time

§

impl Send for Time

§

impl Sync for Time

§

impl Unpin for Time

§

impl UnsafeUnpin for Time

§

impl UnwindSafe for Time

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.