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 chrono::DateTime - Rust 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.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.