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;
}
我在评论我的问题的地方有错误。     

解决方法

您可以使用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等,作为练习留给读者。     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...