2011-05-26 42 views
0

HI,ctime()方法如何打印小时和秒?

我有以下代码:

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; 
} 

我已经在我发表过评论我的问题的地方的错误。

+0

你有这个代码,和...? – Pih 2011-05-26 08:59:10

+0

我有错误在dat [] – marryy 2011-05-26 09:03:05

+0

这是家庭作业 – Blazes 2011-05-26 09:04:55

回答

2

您可以使用localtime()将time_t(自epoch以来的秒数)转换为分解的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等,作为读者的练习。