Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extern crate chrono; // 0.4.6
- use chrono::TimeZone;
- use chrono::Datelike;
- use chrono::{DateTime, Utc, Weekday, Duration};
- fn string_to_datetime(s: String) -> DateTime<Utc> {
- let now = Utc::now();
- match s.as_ref() {
- "this_week" => {
- let this_week = Utc.isoywd(now.iso_week().year(), now.iso_week().week(), Weekday::Fri).and_hms(8, 0, 0);
- if this_week <= now { Utc.isoywd(now.iso_week().year(), now.iso_week().week() + 1, Weekday::Fri).and_hms(8, 0, 0) } else { this_week }
- },
- "next_week" => {
- let this_week = Utc.isoywd(now.iso_week().year(), now.iso_week().week(), Weekday::Fri).and_hms(8, 0, 0);
- if this_week <= now {
- Utc.isoywd(now.iso_week().year(), now.iso_week().week() + 2, Weekday::Fri).and_hms(8, 0, 0)
- } else {
- Utc.isoywd(now.iso_week().year(), now.iso_week().week() + 1, Weekday::Fri).and_hms(8, 0, 0)
- }
- },
- "quarter" => {
- let now = Utc::now();
- match now {
- x if x < Utc.ymd(2018, 12, 28).and_hms(8, 0, 0) => Utc.ymd(2018, 12, 28).and_hms(8, 0, 0),
- x if x < Utc.ymd(2019, 03, 29).and_hms(8, 0, 0) => Utc.ymd(2019, 03, 29).and_hms(8, 0, 0),
- x if x < Utc.ymd(2019, 06, 28).and_hms(8, 0, 0) => Utc.ymd(2019, 06, 28).and_hms(8, 0, 0),
- _ => panic!("Need to update hardcoded quarterly futures for okex.")
- }
- },
- _ => panic!("Unrecognized futures string.")
- }
- }
- fn datetime_to_string(d: DateTime<Utc>) -> String {
- let now = Utc::now();
- if d < now + Duration::weeks(1) {
- "this_week".to_owned()
- } else if d < now + Duration::weeks(2) {
- "next_week".to_owned()
- } else {
- "quarter".to_owned()
- }
- }
- fn main() {
- let d1 = Utc.ymd(2018, 12, 7).and_hms(8, 0, 0);
- let d2 = Utc.ymd(2018, 12, 14).and_hms(8, 0, 0);
- let d3 = Utc.ymd(2018, 12, 28).and_hms(8, 0, 0);
- assert_eq!(datetime_to_string(d1), "this_week");
- assert_eq!(datetime_to_string(d2), "next_week");
- assert_eq!(datetime_to_string(d3), "quarter");
- assert_eq!(string_to_datetime("this_week".to_string()), d1);
- assert_eq!(string_to_datetime("next_week".to_string()), d2);
- assert_eq!(string_to_datetime("quarter".to_string()), d3);
- }
Add Comment
Please, Sign In to add comment