Get current UTC +1 time in Chrono

Hello

I am trying to get the current UCT +1 time.

This is what I currently got:

let offset = chrono::FixedOffset::east(3600);
let current_time = chrono::offset::TimeZone::from_offset(&offset);
println!("{:?}", current_time);

this yields the following error:

type inside `async` block must be known in this context cannot infer type

I guess because this code is ran in a async context.

How would I solve that?

On what statement exactly? It'd also be easier to help if you provided error from cargo check, not from IDE.

Error:

error[E0698]: type inside `async` block must be known in this context
   --> src/main.rs:729:24
    |
729 |     let current_time = chrono::offset::TimeZone::from_offset(&offset);
    |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type
    |
note: the type is part of the `async` block because of this `await`
   --> src/main.rs:966:11
    |
966 |       .run()
    |  ___________^
967 | |     .await
    | |__________^

You need to specify which type implements TimeZone since you aren't calling an instance method.

In this case the type implementing the trait is returned from the function so you can just annotate the binding

let offset = chrono::FixedOffset::east(3600);
let current_time: chrono::FixedOffset = chrono::offset::TimeZone::from_offset(&offset);
println!("{:?}", current_time);
1 Like

I already tried that. But then the output is just the offset +01:00. How do I get the year, month, day,..?

TimeZone::from_offset returns Self, that is, the type which implements TimeZone, and that time is, well, the time zone, not the time. You probably want Utc::now().with_timezone(&timezone).

5 Likes

Thanks all! This works perfectly.

let offset = chrono::FixedOffset::east(3600);
let timezone: chrono::FixedOffset = chrono::offset::TimeZone::from_offset(&offset);
let current_time = chrono::Utc::now().with_timezone(&timezone);
println!("{:?}", current_time);

You don't need from_offset if you're just trying to convert the time with the offset you already created

1 Like