c/c++ 标准日期和时间戳互相转化

来源:互联网 发布:标准篮球场数据 编辑:程序博客网 时间:2024/06/07 18:45

如何获取系统标准时间

time_t rawtime ; 

struct tm * timeinfo; 

time ( &rawtime ); 

timeinfo = localtime ( &rawtime ); 


int Year = timeinfo->tm_year+1900;

int Mon = timeinfo->tm_mon+1;

其余日,时,分,秒都不变。


如何获取系统当前时间戳

 time_t now;                                                                                                                      
 int unixTime = (int)time(&now);




1.时间戳转格式化

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #include <stdio.h>  
  2. #include <time.h>  
    int stamp_to_standard(time_t nSrc, char *sDestTime){
        struct tm p;
        p = *localtime(&nSrc);
        strftime(sDestTime, 1000,"%Y-%m-%d %H:%M:%S", &p);
        return 0;
    }

2.格式化转时间戳

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #include <stdio.h>  
  2. #include <time.h>  
  3.   
  4. int main(int argc, const char * argv[])  
  5. {  
  6.     struct tm* tmp_time = (struct tm*)malloc(sizeof(struct tm));
  7.     strptime("2017-5-1211:13:37","%Y-%m-%d%H:%M:%S",tmp_time);
  8.     time_t t = mktime(tmp_time);  
  9.     printf("%ld\n",t);  
  10.     free(tmp_time);  
  11.     return 0;  
  12. }  
0 0
原创粉丝点击