3

I am displaying a date on the screen using the chrono crate.

The intention is to show the date in the users preferred time or UTC if no is set.

I have the UTC default set up, but I am unsure on the best method to record the user's timezone and how to apply that to the current date.

Note: date might not be set here so I'd prefer to modify date rather than use a different constructor.

let mut date: DateTime<UTC> = UTC::now();

//Convert to the User's Timezone if present
if let Some(user) = user {
    //Extract the timezone
    date.with_timezone(TimeZone::from_offset(&user.timezone));
}

let date_text = date.format("%H:%M %d/%m/%y").to_string();

What I would like is a type to use for user.timezone and an example on how to set the date.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
tl8
  • 537
  • 5
  • 22

1 Answers1

5

You can use the chrono-tz crate, which allows you to convert a string to a timezone with chrono_tz::Tz::from_str("Europe/Berlin"). So all your user has to do is to supply a valid timezone string.

You can then use

fn date_time_str<Tz: chrono::TimeZone>(date: DateTime<Tz>, user: User) -> String {
    if let Some(user) = user {
        if let Ok(tz) = chrono_tz::Tz::from_str(user.timezone) {
            let newdate = date.with_timezone(tz);
            return newdate.format("%H:%M %d/%m/%y").to_string();
        }
    }
    date.format("%H:%M %d/%m/%y").to_string()
}

You cannot modify the original date variable, because the types won't match. The timezone is part of the type. If you move completely to DateTime<chrono_tz::Tz>, then you could modify the variable, but all your uses of DateTime would need to be changed.

oli_obk
  • 28,729
  • 6
  • 82
  • 98