为了账号安全,请及时绑定邮箱和手机立即绑定

您好,请问在C语言中有没有能显示系统日期和时间的函数?

您好,请问在C语言中有没有能显示系统日期和时间的函数?

郎朗坤 2021-12-09 11:07:31
C语言中有没有上述那种函数?如果有,直接给核心代码,需给出头文件和函数原型,如果没有,做个那种功能的代码
查看完整描述

2 回答

?
红颜莎娜

TA贡献1842条经验 获得超12个赞

C语言中读取系统时间的函数为time(),其函数原型为:
#include <time.h>
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 2015

C语言还提供了将秒数转换成相应的时间结构的函数:
struct tm * gmtime(const time_t *timer); //将日历时间转化为世界标准时间(即格林尼治时间)
struct tm * localtime(const time_t * timer); //将日历时间转化为本地时间

将通过time()函数返回的值,转换成时间结构struct tm :
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<time.h>
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*/
}



查看完整回答
反对 回复 2021-12-13
?
杨魅力

TA贡献1811条经验 获得超5个赞

//用标准C实现获取当前系统时间的函数 一.time()函数time(&rawtime)函数获取当前时间距1970年1月1日的秒数,以秒计数单位,存于rawtime 中。
#include "time.h"
void main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "/007The current date/time is: %s", asctime (timeinfo) );
exit(0);
}
=================
#include -- 必须的时间函数头文件
time_t -- 时间类型(time.h 定义是typedef long time_t; 追根溯源,time_t是long)
struct tm -- 时间结构,time.h 定义如下:
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
time ( &rawtime ); -- 获取时间,以秒计,从1970年1月一日起算,存于rawtime
localtime ( &rawtime ); -- 转为当地时间,tm 时间结构
asctime ()-- 转为标准ASCII时间格式:
星期 月 日 时:分:秒 年



查看完整回答
反对 回复 2021-12-13
  • 2 回答
  • 0 关注
  • 246 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信