Converting a String back into chrono::datetime::DateTime

Hi, I'm currently trying to employ a posting system for my website and I need to show the time that has elapsed since a post has been made. I'm using the chrono crate and employ their Utc::now() method to find the current time and storing that value into a redis database. I can find the difference in the time of two different Utc::now() method values by using (time2).signed_duration_since(time1) but because the Utc value is converted into a string when I save it the database and will return as a string when I ask for it back for future use, I need a way to convert the string version of the UTC value back into a UTC value. How would I do this?

Thanks in advance for the help!

1 Like

I guess this depends on how the DateTime<Utc> was turned into a String in the first place. If it’s through the Display implementation, i.e. the string looks like "2020-10-10 21:02:20.346474121 UTC", then simply calling .parse() can give you the DateTime<Utc> back.


use chrono::{Utc, DateTime};

fn main() {
    let now = Utc::now();
    let x: String = format!("{}", now);
    println!("{}", x);
    
    let now_parsed: DateTime<Utc> = x.parse().unwrap();
    
    println!("{}", now_parsed);
}

(playground)

2 Likes

Thanks, this seems to work!

You wouldn't know how to convert a string into a vector would you? Say a string like
let line = "[x, y]".to_string(); Because I store the UTC as a part of a larger string in vector format.

Try this:

use std::str::FromStr;


fn parse<T: AsRef<str>>(input: T) -> Option<Vec<u64>> {
    let input = input.as_ref();
    let trimmed = input.trim();
    let len = trimmed.len();
    // get a str to the middle elements
    // First, check to see that there's atleast 2 elements (braces)
    if len < 2 {
        return None;
    }
    
    let middle = &trimmed[1..(len -1)];
    // replace u64::from_str with whatever data type you need. E.g., usize::from_str
    Some(middle.split(",").filter_map(|piece| u64::from_str(piece).ok()).collect())
}

fn main() {
    let input = "[0,1,2,3,4,5,6,7]";
    let vec = parse(input).unwrap();
    println!("{:?}", vec)
}

This seems to work! Thank you for the help!

1 Like

Just a side question: How are you creating this String representation? Could it be changed? Because if you’d switch to something common like e.g. JSON, there’s the straightforward approach of using serde.

I basically concatenate a bunch of variables to push onto a list on redis. Redis takes in the string and returns a string after a get request.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.