0

How do I change the year in a DateTime<FixedOffset> instance (from the rust crate chrono)?
That is, create a new instance of DateTime<FixedOffset> that copies the month and day from the old instance.

In other words, how would I complete the following code:

fn datetime_set_year(
  datetime: &DateTime<FixedOffset>,
  year: &i32
) -> DateTime<FixedOffset>

The code can ignore exceptional cases like leap days (if that is possible).

E_net4
  • 27,810
  • 13
  • 101
  • 139
JamesThomasMoon
  • 6,169
  • 7
  • 37
  • 63
  • 1
    [`datetime.with_year (year)`](https://docs.rs/chrono/latest/chrono/trait.Datelike.html#tymethod.with_year)? – Jmb Jul 25 '22 at 06:33

1 Answers1

1

The passed DateTime<FixedOffset> instance is taken apart to a Date<FixedOffset> instance and a NaiveTime instance. Then FixedOffset.ymd and .and_time create a new DateTime<FixedOffset> instance using the passed year.

Rust Playground

fn datetime_with_year(datetime: &DateTime<FixedOffset>, year: i32) -> DateTime<FixedOffset> {
    let date: Date<FixedOffset> = datetime.date();
    let time: NaiveTime = datetime.time();
    let fixedoffset: &FixedOffset = datetime.offset();
    match fixedoffset.ymd(year, date.month(), date.day()).and_time(time) {
        Some(datetime_) => {
            eprintln!("fixedoffset.ymd() Some {:?}", datetime_);
            datetime_
        }
        None => {
            eprintln!("fixedoffset.ymd() None");
            datetime.clone()
        }
    }
}

Update: or use datetime.with_year(year) as recommended by @Jmb.

Doh!

JamesThomasMoon
  • 6,169
  • 7
  • 37
  • 63