问题描述
|
嗨,
我有以下代码:
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;
}
我在评论我的问题的地方有错误。
解决方法
您可以使用localtime()将time_t(从纪元到现在的秒数)转换为细分的struct tm实例(或者,是线程安全的localtime_r)。最后,使用strftime()进行字符串格式化。 (无需在任何地方使用ctime)。例如。
#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);
...
错误处理,修复潜在的(琐碎的)错误,转换为std :: string等,作为练习留给读者。