Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add number of seconds to current date using the time-rs crate

Tags:

rust

I want to add 100 seconds to the current time. I'm using this lib

use time::PrimitiveDateTime as DateTime;

pub fn after(start: DateTime) -> DateTime {
    start + 100 seconds // something like this to the start DateTime
}

like image 332
Saurabh Avatar asked Nov 02 '25 03:11

Saurabh


1 Answers

You can create a time::Duration, which can be added to a PrimitiveDateTime. The current time needs to be gotten from an OffsetDateTime, but can easily be used to construct your start:

use time::Duration;
use time::OffsetDateTime;
use time::PrimitiveDateTime as DateTime;

pub fn after(start: DateTime) -> DateTime {
    start + Duration::seconds(100)
}

fn main() {
    let now = OffsetDateTime::now_utc();
    let start = DateTime::new(now.date(), now.time());

    println!("{:?}", now);
    println!("{:?}", start);
    println!("{:?}", after(start));
}

I don't know if you have a reason for using PrimitiveDateTime, but it doesn't contain any time zone info, so I'd suggest replacing those since OffsetDateTime still contains the primitive, and is required to get the current time:

use time::Duration;
use time::OffsetDateTime as DateTime;

pub fn after(start: DateTime) -> DateTime {
    start + Duration::seconds(100)
}

fn main() {
    let now = DateTime::now_utc();

    println!("{:?}", now);
    println!("{:?}", after(now));
}
like image 79
Jeremy Meadows Avatar answered Nov 04 '25 19:11

Jeremy Meadows



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!