C语言获取系统当前时间转化成时间字符串

    因为保存的文件须要加上保存的时间,所以须要一个函数来将系统当前时间获取出来,同一时候转换成时间字符串。详细的时间代码例如以下:


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
#include <stdio.h>
#include <time.h>
int getNowTime(char *nowTime)
{
char acYear[5] = {0};
char acMonth[5] = {0};
char acDay[5] = {0};
char acHour[5] = {0};
char acMin[5] = {0};
char acSec[5] = {0};
time_t now;
struct tm* timenow;
time(&now);
timenow = localtime(&now);
strftime(acYear,sizeof(acYear),"%Y",timenow);
strftime(acMonth,sizeof(acMonth),"%m",timenow);
strftime(acDay,sizeof(acDay),"%d",timenow);
strftime(acHour,sizeof(acHour),"%H",timenow);
strftime(acMin,sizeof(acMin),"%M",timenow);
strftime(acSec,sizeof(acSec),"%S",timenow);
strncat(nowTime, acYear, 4);
strncat(nowTime, acMonth, 2);
strncat(nowTime, acDay, 2);
strncat(nowTime, acHour, 2);
strncat(nowTime, acMin, 2);
strncat(nowTime, acSec, 2);
return 0;
}
int main(int argc, char *argv[])
{
char nowTime[32] = {0};
getNowTime(nowTime);
printf("nowTime is %s.\n", nowTime);
return 0;
}

      在Linux以下和Windows以下都是能够编译和执行的。                 





posted @ 2016-03-05 13:05  yxwkaifa  阅读(4032)  评论(0编辑  收藏  举报