Skip to main content

Duration

Struct Duration 

Source
pub struct Duration {
    pub secs: i64,
    pub nanos: i32,
}
Expand description

A positive duration with second and nanosecond precision

Supports arithmetic operations (+, -, +=, -=) and conversion to/from standard library types.

Use try_new to safely create a Duration from values that may be negative.

§Examples

use rstime::Duration;

let d = Duration::try_new(5, 500_000_000).unwrap();
assert_eq!(d.total_seconds(), 5.5);

Fields§

§secs: i64

Seconds component (must be >= 0 for valid Duration)

§nanos: i32

Nanoseconds component (0..1_000_000_000, must be >= 0)

Implementations§

Source§

impl Duration

Source

pub const ZERO: Duration

Zero duration

Source

pub const SECOND: Duration

One second

Source

pub const MINUTE: Duration

One minute (60 seconds)

Source

pub const HOUR: Duration

One hour (3600 seconds)

Source

pub const DAY: Duration

One day (86400 seconds)

Source

pub fn try_new(secs: i64, nanos: i32) -> Option<Duration>

Try to create a duration from seconds and nanoseconds.

Returns None if the result would be negative (duration must be positive). Normalizes nanoseconds into the 0..1_000_000_000 range.

§Examples
use rstime::Duration;

assert!(Duration::try_new(5, 500_000_000).is_some());
assert!(Duration::try_new(-1, 0).is_none());
Source

pub fn new(secs: i64, nanos: i32) -> Duration

Create a duration from seconds and nanoseconds (panics if negative).

Use try_new for safe creation.

§Panics

Panics if the resulting duration would be negative.

Source

pub fn from_secs(secs: i64) -> Duration

Create from seconds only

Examples found in repository?
examples/demo.rs (line 51)
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 from_millis(ms: i64) -> Duration

Create from milliseconds

Source

pub fn from_nanos(ns: i64) -> Duration

Create from nanoseconds

Source

pub fn from_std(d: StdDuration) -> Duration

Convert from std::time::Duration

Source

pub fn to_std(self) -> Option<StdDuration>

Convert to std::time::Duration, returns None if negative

Source

pub fn to_time_delta(self) -> TimeDelta

Convert to a TimeDelta

Source

pub fn total_seconds(&self) -> f64

Total duration in seconds as a floating-point value

Source

pub fn total_millis(&self) -> i64

Total duration in milliseconds

Examples found in repository?
examples/test_clock.rs (line 30)
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 66)
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}

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 Add for Duration

Source§

type Output = Duration

The resulting type after applying the + operator.
Source§

fn add(self, rhs: Duration) -> Duration

Performs the + operation. Read more
Source§

impl AddAssign for Duration

Source§

fn add_assign(&mut self, rhs: Duration)

Performs the += operation. Read more
Source§

impl Clone for Duration

Source§

fn clone(&self) -> Duration

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 Duration

Source§

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

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

impl Display for Duration

Source§

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

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

impl From<Duration> for TimeDelta

Source§

fn from(d: Duration) -> TimeDelta

Converts to this type from the input type.
Source§

impl Hash for Duration

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 Duration

Source§

fn cmp(&self, other: &Duration) -> 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 Duration

Source§

fn eq(&self, other: &Duration) -> 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 Duration

Source§

fn partial_cmp(&self, other: &Duration) -> 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 Duration

Source§

type Output = Duration

The resulting type after applying the - operator.
Source§

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

Performs the - operation. Read more
Source§

impl SubAssign for Duration

Source§

fn sub_assign(&mut self, rhs: Duration)

Performs the -= operation. Read more
Source§

impl Copy for Duration

Source§

impl Eq for Duration

Source§

impl StructuralPartialEq for Duration

Auto Trait Implementations§

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.