ctime() method how to print the hours and seconds?
HI,
I have the following code:
int main ()
{
time_t rawtime;
time ( &rawtime );
printf ( "The current local time is: %s", ctime (&rawtime) );
std::string datetoString(ctime (&rawtime) );
return 0;
}
std::string datetoString (char dat[])
//how to add ctime(&rawtime) in char dat[]?
{
std::string rez;
struct tm;
strptime(dat, "%d %b %Y %H:%M:%S", &tm);
// what library do i have to inclide for strptime?
rez=tm.tm_mday + "-" + tm.tm_mon +"-"+ tm.tm_year+ hour+min+sec;
//how 开发者_如何学运维to print the hour,minutes and secods?
return rez;
}
i have errors in the places where i've commented my questions.
You can use localtime() to convert a time_t (seconds since the epoch) to a broken-down struct tm instance (or rather, localtime_r which is thread-safe). Finally, use strftime() to do string formatting. (No need to use ctime anywhere). E.g.
#include <time.h>
...
time (&rawtime);
struct tm foo;
struct tm *mytm;
mytm = localtime_r (&rawtime, &foo);
char outstr[200];
strftime(outstr, sizeof(outstr), "%H:%M:%S", mytm);
...
Error handling, fixing potential (trivial) bugs, conversion to std::string etc. left as an exercise for the reader.
精彩评论