rust 在日期范围内循环

vsaztqbk  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(167)

在Python3中,我可以像这样在一个日期范围内循环

import datetime

dt0 = datetime.datetime(2017, 1, 1, 0, 0, 0)
dt1 = datetime.datetime(2017, 1, 5, 0, 0, 0)
dt = dt0
while dt <= dt1:
    print(dt.strftime("%Y-%m-%d %H:%M:%S"))
    dt += datetime.timedelta(days=1)

字符串
在Rust中是否有类似的方法来循环日期?我知道我可以写一个嵌套的循环来循环月份,然后是月份的日期。像这样:

let days = [1, 2, 3, 4, 5, 6, 7,
            8, 9, 10, 11, 12, 13, 14, 
            15, 16, 17, 18, 19, 20, 21,
            22, 23, 24, 25, 26, 27, 28, 29, 30, 31];
let months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
let months_30_days = [4, 6, 9, 11];

for month in months.iter() {
    for day in days.iter() {
        if month == &2 {
            if is_leap_year(year) {
                if day > &29 {
                    continue;
                }
            } else if day > &28 {
                continue;
            }
        } else if months_30_days.contains(&month) && day > &30 {
            continue;
        }

        print!("{:04}-{:02}-{:02} ", year, month, day);
    }
}

fn is_leap_year(year: i32) -> bool {
    if year % 100 == 0 {
        return year % 400 == 0;
    } else {
        return year % 4 == 0;
    }
}


有没有一个更简单的方法来做这件事?

bwleehnv

bwleehnv1#

你可以使用chrono crate来实现:

extern crate chrono; // 0.4.6

use chrono::{Duration, TimeZone, Utc};

fn main() {
    let dt0 = Utc.ymd(2017, 1, 1);
    let dt1 = Utc.ymd(2017, 1, 5);

    let mut dt = dt0;
    while dt <= dt1 {
        println!("{:?}", dt);
        dt += Duration::days(1);
    }
}

字符串
这也可以被 Package 成一个迭代器:

extern crate chrono; // 0.4.6

use chrono::{Date, Duration, TimeZone, Utc};
use std::mem;

struct DateRange(Date<Utc>, Date<Utc>);

impl Iterator for DateRange {
    type Item = Date<Utc>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.0 <= self.1 {
            let next = self.0 + Duration::days(1);
            Some(mem::replace(&mut self.0, next))
        } else {
            None
        }
    }
}

fn main() {
    let dt0 = Utc.ymd(2017, 1, 1);
    let dt1 = Utc.ymd(2017, 1, 5);

    for dt in DateRange(dt0, dt1) {
        println!("{:?}", dt);
    }
}

rbl8hiat

rbl8hiat2#

使用crate time

use time;

/// An iterator between two `[time::Date]` in increments
pub struct DateIter {
    pub from: time::Date,
    pub to: time::Date,
    pub increment: time::Duration,
}

impl Iterator for DateIter {
    type Item = time::Date;

    fn next(&mut self) -> Option<Self::Item> {
        if self.from >= self.to {
            return None;
        }
        let maybe_next = self.from.saturating_add(self.increment);
        self.from = maybe_next;
        (maybe_next < self.to).then_some(maybe_next)
    }
}

字符串

41ik7eoe

41ik7eoe3#

可能有一个crate已经提供了这样的功能,但是如果你想自己实现它,你可以引入一个新的数据类型并实现Iterator-这将是Rust-y的方法。

struct MyDate {
    year: usize, // or allow negatives for B.C.
    month: u8, // or a dedicated Month type limited to 12
    day: u8  // or a dedicated Day type limited to 31
}

impl Iterator for Date {
    type Item = Date;

    fn next(&mut self) -> Option<Date> {
        // conditions for incrementing day, month and year
    }
}

字符串
然后你就可以使用next()在循环中递增它。

相关问题