简体   繁体   English

在计时 DateTime 实例中更新年份

[英]update year in a chrono DateTime instance

How do I change the year in a DateTime<FixedOffset> instance (from the rust crate chrono )?如何更改DateTime<FixedOffset>实例中的年份(来自 rust crate chrono )?
That is, create a new instance of DateTime<FixedOffset> that copies the month and day from the old instance.也就是说,创建一个DateTime<FixedOffset>的新实例,它从旧实例中复制月份和日期。

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).代码可以忽略像闰日这样的例外情况(如果可能的话)。

The passed DateTime<FixedOffset> instance is taken apart to a Date<FixedOffset> instance and a NaiveTime instance.传递的DateTime<FixedOffset>实例被分解为Date<FixedOffset>实例和NaiveTime实例。 Then FixedOffset.ymd and .and_time create a new DateTime<FixedOffset> instance using the passed year .然后FixedOffset.ymd.and_time使用传递的year创建一个新的DateTime<FixedOffset>实例。

Rust Playground Rust游乐场

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.更新:或按照@Jmb 的建议使用datetime.with_year(year)

Doh 😑呵呵😑

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM