当前位置:  开发笔记 > 编程语言 > 正文

遍历日期范围

如何解决《遍历日期范围》经验,为你挑选了1个好方法。

在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;
    }
}

还有更乡村的方式吗?



1> rnstlr..:

您可以使用chrono板条箱:

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 = dt + Duration::days(1);
    }
}

也可以将其包装到迭代器中:

extern crate chrono; // 0.4.6

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

struct DateRange(Date, Date);

impl Iterator for DateRange {
    type Item = Date;
    fn next(&mut self) -> Option {
        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);
    }
}

推荐阅读
围脖上的博博_771
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有