61

I am trying to find the preferred way to add days to a Chrono UTC. I want to add 137 days to the current time:

let dt = UTC::now();
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
schmoopy
  • 6,419
  • 11
  • 54
  • 89

2 Answers2

85

Just use Duration and appropriate operator:

use chrono::{Duration, Utc};

fn main() {
    let dt = Utc::now() + Duration::days(137);

    println!("today date + 137 days {}", dt);
}

Test on playground.

Stargateur
  • 24,473
  • 8
  • 65
  • 91
  • 7
    Thank you, i missed the arithmetic part. Great community, great crates. The documentation format tho feels like I am reading MSDN. Thanks for the correct easy answer, a lot better than what i was doing after reading through those docs for the 11th time :-) – schmoopy Jun 22 '17 at 23:44
  • Wow! This is much better than momentJS – Gus Jun 22 '22 at 19:19
  • It's worth noting that the "+ Duration" function is implemented for DateTime<_>, but the reverse is NOT true, so while ```Utc::now() + Duration::days(137)``` works the reverse does not: ```Duration::days(137) + Utc::now()``` – capveg Aug 29 '23 at 16:13
45

I just wanted to improve on @Stargateur answer. There is no need to use time crate, since chrono crate has Duration struct in it:

extern crate chrono;

use chrono::{Duration, Utc};

fn main() {
    let dt = Utc::now() + Duration::days(137);

    println!("{}", dt);
}

Another test on playground

Yerke
  • 2,071
  • 2
  • 25
  • 23
  • 1
    Note that currently `Duration` is just a wrapper to `time::Duration`, there could be breaking change by using `Duration` directly – Stargateur Apr 12 '18 at 08:45
  • 11
    @Stargateur If there was a breaking change between chrono and time crates, I'd think that using the, using chrono's `Duration` lets me rely on the chrono crate to fix the problem, so I can just update that one dependency without having to make a code change myself. – Peter Hall Apr 12 '18 at 14:49
  • 2
    As of May/2020, using `chrono::Duration` is actually necessary, since `time::Duration` doesn't implement the addition trait. – Marcus May 14 '20 at 20:54