首页 > 代码库 > C语言获取系统当前时间转化成时间字符串

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下面都是可以编译和运行的。                 





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