Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 976
Samson G. Avatar asked May 22 '19 20:05

Samson G.


1 Answers

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
like image 165
Leśny Rumcajs Avatar answered Oct 22 '22 07:10

Leśny Rumcajs