Skip to content

Instantly share code, notes, and snippets.

@indykish
Forked from rust-play/playground.rs
Created December 31, 2019 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indykish/1bbb73ae22529a31b533fc763943e80d to your computer and use it in GitHub Desktop.
Save indykish/1bbb73ae22529a31b533fc763943e80d to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use chrono::prelude::*;
use regex::Regex;
#[macro_use]
extern crate lazy_static; // 1.4.0
/// A function when provided with the date in the format
/// YYYY/MM/DD or YYYY-MM-DD returns an output as YYYYMMDD
/// If the date is invalid it returns the today (now) YYYYMMDD
/// Hmm, I think its best to send back as none.
pub fn date_in_cobol_format(text: &str) -> Option<String> {
regex_date_in_cobol_format(text).map(|c| c.as_cobol())
}
/// A function when provided with the date in the format
/// YYYY/MM/DD or YYYY-MM-DD returns an output as YYYYMMDD
/// If the date is invalid it returns the today (now) YYYYMMDD
/// Hmm, I think its best to send back as none.
pub fn tuples_date_in_cobol_format(text: &str) -> Option<(i32, u32, u32)> {
regex_date_in_cobol_format(text).map(|c| (c.yyyy(), c.mm(), c.dd()))
}
/// A function when provided with the date in the format
/// YYYY/MM/DD or YYYY-MM-DD returns an output as YYYYMMDD
/// If the date is invalid it returns the today (now) YYYYMMDD
/// Hmm, I think its best to send back as none.
fn regex_date_in_cobol_format(text: &str) -> Option<CobolDate> {
lazy_static! {
static ref RE: Regex = Regex::new(
r"(?x)
(?P<year>\d{4}) # the year
[/.-]
(?P<month>\d{2}) # the month
[/.-]
(?P<day>\d{2}) # the day
"
)
.unwrap();
}
RE.captures(text).map(|caps| CobolDate {
yyyy_str: caps["year"].to_string(),
mm_str: caps["month"].to_string(),
dd_str: caps["day"].to_string(),
})
}
#[derive(Debug, Clone)]
struct CobolDate {
yyyy_str: String,
mm_str: String,
dd_str: String,
}
impl CobolDate {
fn yyyy(&self) -> i32 {
self.yyyy_str.parse::<i32>().unwrap_or(Utc::today().year())
}
fn mm(&self) -> u32 {
self.mm_str.parse::<u32>().unwrap_or(Utc::today().month())
}
fn dd(&self) -> u32 {
self.dd_str.parse::<u32>().unwrap_or(Utc::today().day())
}
fn as_cobol(&self) -> String {
let y = self.yyyy().clone();
let m = self.mm().clone();
let d = self.dd().clone();
Utc.ymd(y, m, d).and_hms(0, 0, 0).format("%Y%m%d").to_string()
}
}
fn main() {
println!("=========== Date !");
let b = DateTime::parse_from_str("2014-11-28 21:00:09 +09:00", "%Y-%m-%d %H:%M:%S %z").unwrap();
println!("* {:?}", b.format("%Y/%m/%d").to_string());
// println!("{:?}", date_in_cobol_format("05/21/1982"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment