DateTime::sub. How to use it?

I have a DateTime `object from which I want to subtract one second.

Given that dt is a DateTime I have been doing:
let dt = dt.sub(Duration::seconds(1)

I get the error: error[E0599]: no method named sub found for type chrono::DateTime<chrono::Local> in the current scope

At https://docs.rs/chrono/0.4.0/chrono/struct.DateTime.html#method.sub there is the method.

I am perplexed

First of all, you don’t have to call this method explicitly. It is called whenever you perform a subtraction operation. I.e., you can simply do:

let dt = dt - Duration::seconds(1);

And this should work.

If, however, you want to use the method explicitly, note that it doesn’t belong to the DateTime itself, but rather to the std::ops::Sub trait, and trait methods may be used only if the method is in scope. So, if you add

use std::ops::Sub;

to your file (as the error message should have suggested), your code should also work.
Playground for the second case

2 Likes

You could just use the - operator. If you don’t you will have to import the std::ops::Sub trait to use the method.