需求:
拟生成以下markdown管理小工具,这也是我日常工作日程表。
可以输入任意时间段,运行后就可以生成以上的markdown文件。
一、toml
[package]
name = "rust-workfile"
version = "0.1.0"
edition = "2021"[dependencies]
chrono ="0.4.38"
二、main.rs
// 假设 从2025-01-01到2016-01-01
use std::fs::OpenOptions;
use std::collections::HashMap;
use std::io::Write;
use chrono::prelude::*;
fn main() {let file_name = "./workfile_2025.md" ;let start_date= "2025-01-01";let end_date = "2026-01-01";write_markdown_file(file_name,start_date,end_date);
}
fn write_markdown_file(file_name: &str,start_date:&str, end_date:&str){let mut _file = OpenOptions::new().read(true).write(true).create(true).open(file_name).unwrap();let mut buffer = String::new();buffer.push_str("# workfile \n\n");let start_date: NaiveDate = NaiveDate::parse_from_str(start_date, "%Y-%m-%d").unwrap();let end_date : NaiveDate = NaiveDate::parse_from_str(end_date, "%Y-%m-%d").unwrap();let delta_days = end_date.signed_duration_since(start_date).num_days();let weeks_num = (delta_days as f32 / 7.0 ).ceil() as usize;let start_week = start_date.week(Weekday::Mon);let first_day = start_week.first_day();let first_days = first_day.iter_weeks().take(weeks_num).collect::<Vec<NaiveDate>>();let mut month_map :HashMap<String,bool> = HashMap::new();for first_date in first_days{let format_year_month = format!("## {} \n\n",first_date.format("%Y年%m月"));if !month_map.contains_key(&format_year_month) {buffer.push_str(&format_year_month); month_map.insert(format_year_month,true);}let week_dates :Vec<NaiveDate> = first_date.iter_days().take(5).collect();//### [2024_12_2-2024-12_6]let format_week_start_end = format!("### [{}-{}] \n\n",week_dates[0].format("%Y_%m_%d"),week_dates[4].format("%Y_%m_%d")); buffer.push_str(&format_week_start_end);// #### 周一[2024_12_2]:for week_date in week_dates{let str_week_day = get_weekday_string(&week_date);let format_date = format!("#### {}[{}]\n\n",str_week_day,week_date.format("%Y_%m_%d"));buffer.push_str(&format_date);}}_file.write(&buffer.as_bytes()).expect("write failed!");println!("文件已经生成!");
}
fn get_weekday_string(date :&NaiveDate) ->&str{let weekday = date.weekday();let weekday_str = match weekday{Weekday::Mon => "周一",Weekday::Tue => "周二",Weekday::Wed => "周三",Weekday::Thu => "周四",Weekday::Fri => "周五",Weekday::Sat => "周六",Weekday::Sun => "周日", _ => "Unknown",};weekday_str
}