about summary refs log tree commit diff
path: root/timeparse/src/format.rs
blob: 3b4ab15703b081b25b81849e84659f378d68c898 (plain)
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use time::{Date, OffsetDateTime, UtcOffset, format_description::well_known};

use crate::{MONTHS, which_offset};

pub fn human_long(datetime: &OffsetDateTime) -> String {
	let year = datetime.year();
	let month = MONTHS[datetime.month() as usize - 1][1];
	let day = datetime.day();
	let weekday = datetime.weekday();

	format!("{weekday} {day}, {month} {year}")
}

pub fn human_with_time(datetime: &OffsetDateTime) -> String {
	let date = human_long(datetime);
	let (h, m, s) = datetime.to_hms();
	let offset = match which_offset(&datetime.offset()) {
		None => offset(&datetime.offset()),
		Some((name, _)) => name.to_owned(),
	};

	format!("{date} {h:02}:{m:02}:{s:02} {offset}")
}

fn offset(offset: &UtcOffset) -> String {
	let (h, m, s) = offset.as_hms();
	if s == 0 {
		if m == 0 {
			format!("{h:+}")
		} else {
			format!("{h:+}:{:02}", m.abs())
		}
	} else {
		format!("{h:+}:{:02}:{:02}", m.abs(), s.abs())
	}
}

pub fn iso8601(datetime: &OffsetDateTime) -> String {
	datetime
		.format(&well_known::Iso8601::DATE_TIME_OFFSET)
		.unwrap()
}

pub fn iso_date(date: &Date) -> String {
	let year = date.year();
	let month = date.month();
	let day = date.day();
	format!("{year}-{month:02}-{day:02}")
}