您的位置:首页 > 其它

如何获取当前时间

2017-06-17 15:59 120 查看
                有时候代码中需要获取当前时间,那怎么做呢,今天来学习一下。

#include<stdio.h>
#include<time.h>

void unixTime2Str(int n, char strTime[], int bufLen)
{
struct tm tm = *localtime((time_t *)&n);//localtime函数返回当前时区的时间,返回值为struct tm*

//strftime函数对tm结构所代表的时间和日期进行格式编排,其结果放在字符串strTime中
strftime(strTime, bufLen - 1, "%Y-%m-%d-%w %H:%M:%S", &tm);
strTime[bufLen - 1] = '\0';
}

int main()
{
char strTime[100] = {0};
int now = time(NULL);//time()函数来获得日历时间,time_t实际上就是长整型long int,这种类型就是用来存储从1970年到现在经过了多少秒
unixTime2Str(now, strTime, sizeof(strTime));
printf("%s\n", strTime);

return 0;
}打印:星期6-2017-06-17-6 15:41:36
看看tm结构体

struct tm

{

    int tm_sec;  //秒,正常范围0-59, 但允许至61

    int tm_min;  //分钟,0-59

    int tm_hour; //小时, 0-23

    int tm_mday; //日,即一个月中的第几天,1-31

    int tm_mon;  //月, 从一月算起,0-11  1+p->tm_mon;

    int tm_year;  //年, 从1900至今已经多少年  1900+ p->tm_year;

    int tm_wday; //星期,一周中的第几天, 从星期日算起,0-6

    int tm_yday; //从今年1月1日到目前的天数,范围0-365

    int tm_isdst; //日光节约时间的旗标

}

struct tm tm中,struct tm为tm结构体,后面的tm为结构体变量。time(NULL)返回一个时间戳,在linux下用date -d@时间戳 可以打印出这个对应正常时间。注意%Y-%m-%d-%w %H:%M:%S格式中的大小写。

学习地址:http://blog.csdn.net/stpeace/article/details/73065144

               
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: