Skip to content

Commit

Permalink
Date time module
Browse files Browse the repository at this point in the history
  • Loading branch information
el7cosmos committed Sep 17, 2020
1 parent cdb07c9 commit 12b8d00
Show file tree
Hide file tree
Showing 2 changed files with 105 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/date.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use chrono::{Local, NaiveDate, ParseError, ParseResult};
use serde::export::Formatter;

#[derive(Copy, Clone, Debug)]
pub(super) struct Date(NaiveDate);

impl Default for Date {
fn default() -> Self {
Date {
0: Local::now().date().naive_local(),
}
}
}

impl std::fmt::Display for Date {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
self.0.fmt(f)
}
}

impl std::str::FromStr for Date {
type Err = ParseError;

fn from_str(s: &str) -> ParseResult<Date> {
match NaiveDate::from_str(s) {
Ok(naive) => Ok(Date { 0: naive }),
Err(err) => Err(err),
}
}
}

impl Into<NaiveDate> for Date {
fn into(self) -> NaiveDate {
self.0
}
}

#[cfg(test)]
mod tests {
use crate::date::Date;
use chrono::Local;

#[test]
fn default() {
assert_eq!(Date::default().0, Local::now().date().naive_local())
}
}
58 changes: 58 additions & 0 deletions src/time.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use chrono::{Local, NaiveTime, ParseError, ParseResult};

#[derive(Copy, Clone, Debug)]
pub(super) struct Time(NaiveTime);

impl Default for Time {
fn default() -> Self {
Time {
0: Local::now().time(),
}
}
}

impl std::fmt::Display for Time {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.0.fmt(f)
}
}

impl std::str::FromStr for Time {
type Err = ParseError;

fn from_str(s: &str) -> ParseResult<Time> {
match NaiveTime::parse_from_str(s, "%R") {
Ok(naive) => Ok(Time { 0: naive }),
Err(_) => match NaiveTime::from_str(s) {
Ok(naive) => Ok(Time { 0: naive }),
Err(err) => Err(err),
},
}
}
}

impl Into<NaiveTime> for Time {
fn into(self) -> NaiveTime {
self.0
}
}

impl Into<Option<NaiveTime>> for Time {
fn into(self) -> Option<NaiveTime> {
Some(self.0)
}
}

#[cfg(test)]
mod tests {
use crate::time::Time;
use chrono::{Local, Timelike};

#[test]
fn default() {
assert_eq!(
Time::default().0.with_nanosecond(0),
Local::now().time().with_nanosecond(0)
)
}
}

0 comments on commit 12b8d00

Please sign in to comment.