How to convert an i32 to u32

How to convert these current_year, current_month and current_day variable bellow to u32

chrono::prelude::*;


fn main() {
  let current_date: DateTime < Local > = Local::now();
  let current_year = current_date.year();
  let current_month = current_date.month();
  let current_day = current_date.day();
}

current_month and current_day are already u32. You can cast the year to u32 using the as operator.

  let current_year = current_date.year() as u32;
  let current_month = current_date.month();
  let current_day = current_date.day();

is there any other method to convert it besides "as" ?

You can also use try_from, which returns a Result, which will be an Err for negative numbers, if for some reason you are concerned about that:

fn main() {
    dbg!(u32::try_from(1i32));
    dbg!(u32::try_from(-1i32));
}

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.