8

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?

E_net4
  • 27,810
  • 13
  • 101
  • 139
Samson G.
  • 369
  • 1
  • 3
  • 7

1 Answers1

8

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
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Leśny Rumcajs
  • 2,259
  • 2
  • 17
  • 33
  • 1
    That `round_subsecs(6)` can be enabled also by `use chrono::{SubsecRound, Utc};`. This functionality is useful with the Postgres types `TIMESTAMPTZ` having 6 digits instead of the usual `chrono` type `DateTime` with 9 digits causing e.g. `assert_eq!(...)` to fail. – TPPZ Oct 06 '21 at 15:27