Samson G.
Samson G.

Reputation: 459

How can I round a chrono::Datetime to the nearest second?

I want to get the current time rounded to the nearest second using the chrono crate but I don't know how to strip or round the result of chrono::UTC.now().

It doesn't seem like there are any operations to modify an existing `DateTime.

chrono::UTC.now()

Returns: 2019-05-22T20:07:59.250194427Z

I want to get: 2019-05-22T20:07:59.000000000Z

How would I go about doing that in the most efficient way without breaking up the DateTime value into its components and recreating it?

Upvotes: 8

Views: 3070

Answers (1)

Leśny Rumcajs
Leśny Rumcajs

Reputation: 2516

Use the round_subsecs method with 0 as an argument.

use chrono::prelude::*;

fn main() {
    let utc: DateTime<Utc> = Utc::now().round_subsecs(0);
    println!("{}", utc);
}

The result is:

2019-05-22 20:50:46 UTC

Upvotes: 9

Related Questions