Convert hour, min, day, month, year, time_zone to UTC

This is a fairly simple question, but I failed to understand how I can do it from the Chrono crate.

Assume I have

let yyyy = 2024;
let mm = 5;
let dd = 1;
let hour = 4;
let min = 30;
let time_zone = 7;

I need to get the time at UTC, which is basically something like: 21:30 2024/04/30 UTC
Except for the fact I don't know how to do it.

Googling give me the option to convert it from RFC3339, but why? Such a simple task with no straight forward option?

Asking Google Bard, it tells me to do

let date = NaiveDate::from_ymd_opt(yyyy, mm, dd).unwrap();
let time = NaiveTime::from_hms_opt(hour, min, 0).unwrap();
let naive_datetime = NaiveDateTime::new(date, time);
let utc_datetime = DateTime::<Utc>::from_naive_utc_and_offset(naive_datetime, Utc);

Which is completely wrong because I provide the time at GMT +7, not UTC.
(ChatGPT is not free in my country :frowning: )

So any help?
Thank you

Edit, I selected the Solution, but just to save a click for future reference, or help the crawl engine when googling, this is the answer:

let yyyy = 2024;
let mm = 5;
let dd = 1;
let hour = 4;
let min = 30;
let time_zone = 7;

    let date = NaiveDate::from_ymd_opt(yyyy, mm, dd).unwrap();
    let time = NaiveTime::from_hms_opt(hour, min, 0).unwrap();
    let naive_datetime = NaiveDateTime::new(date, time);
    let my_tz = FixedOffset::east_opt(time_zone * 3600).unwrap();
    let local_datetime = naive_datetime.and_local_timezone(my_tz).unwrap();
    let utc_naive = local_datetime.naive_utc();
    let utc_datetime = Utc.from_local_datetime(&utc_naive);
    dbg!(local_datetime);
    dbg!(utc_naive);
    dbg!(utc_datetime);

Well, if you have a UTC answer, you have all you need: just construct it with the appropriate timezone instead of UTC in the first place (then convert it to UTC).

Yeah I presume I should replace the Utc in the from_naive_utc_and_offset with something. However, I tried:

let offset = FixedOffset::east_opt(chrono::Duration::hours(time_zone).num_seconds() as i32).unwrap();
let gmt_datetime = DateTime::<Utc>::from_naive_utc_and_offset(naive_datetime, offset);

This is wrong because the function expected `Utc`, but found `FixedOffset` .
So, yeah :<

You want DateTime::naive_utc().

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.