c语言获得系统时间

注:该贴转自:https://zhidao.baidu.com/question/558299804.html

C语言中读取系统时间的函数为time(),其函数原型为:#include time_t time( time_t * ) ;

time_t就是long,函数返回从1970年1月1日(MFC是1899年12月31日)0时0分0秒,到现在的的秒数。

可以调用ctime()函数进行时间转换输出:char * ctime(const time_t *timer);

将日历时间转换成本地时间,按年月日格式,进行输出,如:Wed Sep 23 08:43:03 2015C语言还提供了将秒数转换成相应的时间结构的函数:

struct tm * gmtime(const time_t *timer); //将日历时间转化为世界标准时间(即格林尼治时间)

struct tm * localtime(const time_t * timer); //将日历时间转为本地时间将通过time()函数返回的值,转成时间结构structtm :

struct tm {int tm_sec; /* 秒 – 取值区间为[0,59] */

int tm_min; /* 分 - 取值区间为[0,59] */

int tm_hour; /* 时 - 取值区间为[0,23] */

int tm_mday; /* 一个月中的日期 - 取值区间为[1,31] */

int tm_mon; /* 月份(从一月开始,0代表一月) - 取值区间为[0,11] */

int tm_year; /* 年份,其值等于实际年份减去1900 */

int tm_wday; /* 星期 – 取值区间为[0,6],其中0代表星期天,1代表星期一,以此类推 */

int tm_yday; /* 从每年的1月1日开始的天数 – 取值区间为[0,365],其中0代表1月1日,1代表1月2日,以此类推 */

int tm_isdst; /* 夏令时标识符,实行夏令时的时候,tm_isdst为正。不实行夏令时的进候,tm_isdst为0;不了解情况时,tm_isdst()为负。*/};

编程者可以根据程序功能的情况,灵活的进行日期的读取与输出了。

下面给出一段简单的代码:

#include

int main()

{

    time_t timep;

    struct tm *p;

    time (&timep);

    p=gmtime(&timep);

    printf("%d\n",p->tm_sec); /*获取当前秒*/

    printf("%d\n",p->tm_min); /*获取当前分*/

    printf("%d\n",8+p->tm_hour);/*获取当前时,这里获取西方的时间,刚好相差八个小时*/

    printf("%d\n",p->tm_mday);/*获取当前月份日数,范围是1-31*/

    printf("%d\n",1+p->tm_mon);/*获取当前月份,范围是0-11,所以要加1*/

    printf("%d\n",1900+p->tm_year);/*获取当前年份,从1900开始,所以要加1900*/

    printf("%d\n",p->tm_yday); /*从今年1月1日算起至今的天数,范围为0-365*/

}

你可能感兴趣的:(c语言获得系统时间)