Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created September 21, 2019 11:28
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 rust-play/750ec92f41d19231f2fcf1e7ef3c330c to your computer and use it in GitHub Desktop.
Save rust-play/750ec92f41d19231f2fcf1e7ef3c330c to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#[test]
fn basic_test() {
assert_eq!(day_of_year("2019-01-09".to_string()), 9);
assert_eq!(day_of_year("2019-02-10".to_string()), 41);
assert_eq!(day_of_year("2003-03-01".to_string()), 60);
assert_eq!(day_of_year("2004-03-01".to_string()), 61);
}
pub fn day_of_year(date: String) -> i32 {
let vec: Vec<&str> = date.split("-").collect();
[(vec[0],vec[1],vec[2])].iter().map(|(year,month,day)|
match month {
&"01" => day.parse().unwrap(),
&"02" => day.parse().unwrap() + 31,
_ => match year.parse().unwrap(){
y if y%4==0&&y%100!=0
||y%400==0&&y%3200!=0
||y%172800==0=>
match month {
&"03" => day.parse().unwrap()+31+29,
&"04" => day.parse().unwrap()+31+29+31,
&"05" => day.parse().unwrap()+31+29+31+30,
&"06" => day.parse().unwrap()+31+29+31+30+31,
&"07" => day.parse().unwrap()+31+29+31+30+31+30,
&"08" => day.parse().unwrap()+31+29+31+30+31+30+31,
&"09" => day.parse().unwrap()+31+29+31+30+31+30+31+31,
&"10" => day.parse().unwrap()+31+29+31+30+31+30+31+31+30,
&"11" => day.parse().unwrap()+31+29+31+30+31+30+31+31+30+31,
&"12" => day.parse().unwrap()+31+29+31+30+31+30+31+31+30+31+30
},
_ => match month{
&"03" => day.parse().unwrap()+31+28,
&"04" => day.parse().unwrap()+31+28+31,
&"05" => day.parse().unwrap()+31+28+31+30,
&"06" => day.parse().unwrap()+31+28+31+30+31,
&"07" => day.parse().unwrap()+31+28+31+30+31+30,
&"08" => day.parse().unwrap()+31+28+31+30+31+30+31,
&"09" => day.parse().unwrap()+31+28+31+30+31+30+31+31,
&"10" => day.parse().unwrap()+31+28+31+30+31+30+31+31+30,
&"11" => day.parse().unwrap()+31+28+31+30+31+30+31+31+30+31,
&"12" => day.parse().unwrap()+31+28+31+30+31+30+31+31+30+31+30
}
}
}
).collect()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment