Last active
July 29, 2018 18:25
-
-
Save gentoid/81bee8e224b259fe5b1182c608a523a4 to your computer and use it in GitHub Desktop.
Human readable time diff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mod time_diff; | |
use time_diff::TimeDiff; | |
fn main() { | |
let td = TimeDiff::new(1234123); | |
let td2 = TimeDiff::new(1233); | |
println!("First diff is {}", td); | |
println!("Second diff is {}", td2); | |
println!("Sum of that diffs is {}", td + td2); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fmt; | |
use std::ops::Add; | |
pub struct TimeDiff { | |
value: u32, | |
seconds: u32, | |
minutes: u32, | |
hours: u32, | |
days: u32, | |
} | |
struct RemMod { | |
remr: u32, | |
modl: u32, | |
} | |
impl RemMod { | |
fn from(amount: u32, div_by: u32) -> RemMod { | |
let modl = amount / div_by; | |
let remr = amount - modl * div_by; | |
RemMod { remr: remr, modl: modl } | |
} | |
} | |
impl TimeDiff { | |
pub fn new(diff: u32) -> Self { | |
let RemMod { remr: seconds, modl: minutes } = RemMod::from(diff, 60); | |
let RemMod { remr: minutes, modl: hours } = RemMod::from(minutes, 60); | |
let RemMod { remr: hours, modl: days } = RemMod::from(hours, 24); | |
TimeDiff { | |
value: diff, | |
seconds: seconds, | |
minutes: minutes, | |
hours: hours, | |
days:days, | |
} | |
} | |
pub fn is_zero(&self) -> bool { | |
self.value == 0 | |
} | |
} | |
impl Add for TimeDiff { | |
type Output = Self; | |
fn add(self, other: TimeDiff) -> Self { | |
Self::new(self.value + other.value) | |
} | |
} | |
impl fmt::Display for TimeDiff { | |
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | |
if self.is_zero() { | |
write!(fmt, "Is kind of zero seconds"); | |
} | |
else { | |
let mut parts = vec![]; | |
if self.days > 0 { | |
parts.push(format!("{} days", self.days)); | |
} | |
if self.hours > 0 { | |
parts.push(format!("{} hours", self.hours)); | |
} | |
if self.minutes > 0 { | |
parts.push(format!("{} minutes", self.minutes)); | |
} | |
if self.seconds > 0 { | |
parts.push(format!("{} seconds", self.seconds)); | |
} | |
write!(fmt, "{}", parts.join(", ")); | |
} | |
Ok(()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment