Skip to content

Instantly share code, notes, and snippets.

@diwic
Created August 15, 2016 13:17
Show Gist options
  • Save diwic/5c20a283ca3a03752e1a27b0f3ebfa30 to your computer and use it in GitHub Desktop.
Save diwic/5c20a283ca3a03752e1a27b0f3ebfa30 to your computer and use it in GitHub Desktop.
Calendar example
use chrono::{NaiveDate, Datelike, Duration};
use std::cmp;
fn format_year(y: i32, cols: usize) -> String {
let mut day: Vec<_> = (0..12).into_iter().map(|i| {
let first = NaiveDate::from_ymd(y, i+1, 1);
(first, first - Duration::days(first.weekday().num_days_from_sunday() as i64))
}).collect();
let mut s = String::new();
let mut startm = 0;
loop {
let endm = cmp::min(startm+cols, 12);
for c in startm..endm { s += &format!("{}{:^21}", if c > startm {" "} else {""}, MONTH_NAMES[c]); }
s += "\n";
loop {
let mut moredays = false;
for c in startm..endm {
if c > startm { s += " "; }
let d = &mut day[c];
for _ in 0..7 {
s += if d.0.month() == d.1.month() { &format!("{:>3}", d.1.day()) } else {" "};
d.1 = d.1 + Duration::days(1);
}
moredays |= d.0.month() == d.1.month() || d.1 < d.0;
}
s += "\n";
if !moredays { break; }
}
startm += cols;
if startm >= 12 { return s; }
s += "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment