Newbie: help with getting a String from current time

I am very new to Rust and learning it, I seem to be hitting a stumbling block.

I need a String with the current time/date.

I can get at the time and date in a numbr of ways. I am able to println!() without problems but I have spent a few hours now trying to get a String or str of the date and or time without success. I have looked at and tried with the crate chrono. I can easily get at the date and time and format it to print on stdout but I am unable to get it in a string for use elsewhere in the program I am trying to write as a first non-trivial one.

My use case is rather simple. I want to use a close approximation of the hours and minutes at which I write a file to use in the file name.

I am trying to reproduce in rust a program I wrote a while ago whilst I was learning golang which I released open sourced and will do the same with the rust version. I am enjoying many aspects of rust, but this is really frustrating me and has cost me heaps of time already. I suspect the issue has to be with ownership and I sort of understand that, but I cannot find a solution, less an idiomatic or elegant one.

Any help would be greatly appreciated!

.

Have you tried the format! macro? It works like print! but returns a String.

Using chrono:

use chrono::prelude::*;
let date_as_string = Utc::now().to_string();

Yes, I did try and it seems that format returns a fn and not a String in my case!?

Thanks a lot H2C03!

That did the trick. I simply wasn't aware of the chrono::prelude crate.

Could you share the code? This sounds really strange.

1 Like

either let mystring = format!("{:?}", Utc::now().to_string());
or let myssring: String = format!("{:?}", Utc::now().to_string());

         println!("{}", mystring());

gives me:

error: expected function, found std::string::String
label: std::string::String defined here

You put parenthesis by mistake: mystring()

1 Like

This gives default formatting, but are there are a number of other methods available other than to_string, if something different is needed/preferred:

(Note that Utc::now() returns a DateTime instance, so this is where to look for information about conversion to strings.)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.