[SOLVED] Date to Epoch Unix Timestamp Converter


I’m searching a way to convert a date into a Unix timestamp. I’ve given a look to the chrono crate but I haven’t find what could help me with this.

pub fn UnixCoverter(date: String) -> i64 {

The format of the date is:
mm/dd/yyyy HH:MM //[7/18/2017 15:09]

The output should be 1500383340.

Do you have any tips??
Thank you in advance!!


Did you see https://docs.rs/chrono/0.4.0/chrono/struct.DateTime.html#method.timestamp? As far as I can tell, that should do it.


As @KillTheMule said, you can get correct epoch by using timestamp, parsing should be easily doable after reading https://docs.rs/chrono/0.4.0/chrono/format/index.html


Ok, I’ll give a look and I’ll try to figure it out…
Thank you @KillTheMule @NobbZ


I would like to share my solution:

pub fn unix_coverter(date: String) -> i64 {

    let full_date : Vec<_> = date.split("/").collect();
    let temp_yt : Vec<_> = full_date[2].split_whitespace().collect();
    let temp_t : Vec<_> = temp_yt[1].split(":").collect();

    let date_fmt = NaiveDate::from_ymd(temp_yt[0].parse::<i32>().unwrap(), full_date[0].parse::<u32>().unwrap(), full_date[1].parse::<u32>().unwrap()).and_hms(temp_t[0].parse::<u32>().unwrap(), temp_t[1].parse::<u32>().unwrap(), 00);
    let date_unix = NaiveDateTime::timestamp(&date_fmt);
    let result_unix = date_unix * 1000000000;

I do this this step since I need milliseconds too:
date_unix * 1000000000000


Those aren’t milliseconds… Milliseconds where only seconds * 1_000! If recall correctly you are making femto seconds from it. A single CPU cycle takes longer, even on modern multi-GHz machines.

Also getting the date might be much simpler by DateTime.parse_from_str(s, "%-m/%-d/%Y %H:%M").


Yes… You are definitely right… Thanks again