Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ convert time_t to string and back again

Tags:

c++

time

I want to convert a time_t to a string and back again.
I'd like to convert the time to a string using ctime().
I can't seem to find anything on google or the time.h header file, any ideas?
Basically what I'm trying to do is store a date in a file, and then read it back so I can use it as a time_t again.
Also, no library references outside of std,mfc.
One more note, this will have to function on Windows xp and above and that's it.

Edit

All I want to do is convert a time_t into a string(I don't care if it's human readable) and then convert it back to a time_t. I'm basically just trying to store the time_t into a file and read it again(but I don't want any code for that, as there will be more info in the file besides a time_t).

like image 469
Kelly Elton Avatar asked Aug 18 '11 20:08

Kelly Elton


People also ask

How to convert time to string in c?

The ctime() function converts the time value pointed to by time to local time in the form of a character string. A time value is usually obtained by a call to the time() function. The ctime() function uses a 24-hour clock format.

How to convert system time to string?

String ^strT = nowT. ToString();

What is the use of ctime()?

The ctime() function in C++ converts the given time since epoch to a calendar local time and then to a character representation. A call to ctime(time) is a combination of asctime() and localtime() functions, as asctime(localtime(time)) .

What is time_ t in c?

Description. The C library function time_t time(time_t *seconds) returns the time since the Epoch (00:00:00 UTC, January 1, 1970), measured in seconds. If seconds is not NULL, the return value is also stored in variable seconds.


2 Answers

You'll have to write your own function to do that. These functions convert any primitive type (or any type which overloads operator<< and/or operator>>) to a string, and viceversa:

template<typename T>
std::string StringUtils::toString(const T &t) {
    std::ostringstream oss;
    oss << t;
    return oss.str();
}

template<typename T>
T StringUtils::fromString( const std::string& s ) {
    std::istringstream stream( s );
    T t;
    stream >> t;
    return t;
}
like image 117
dario_ramos Avatar answered Oct 13 '22 21:10

dario_ramos


ctime() returns a pointer to a character buffer that uses a specific formatting. You could use sprintf() to parse such a string into its individual portions, store them in a struct tm, and use mktime() to convert that to a time_t.

like image 26
Remy Lebeau Avatar answered Oct 13 '22 23:10

Remy Lebeau