0
点赞
收藏
分享

微信扫一扫

C 语言获取系统时间

time函数:获取当前日期。

头文件

原型

说明

返回值

#include <time.h>

time_t time(time_t *timer)

求出日期时间。

返回当前的日期时间。若日期时间无效,则返回-1。若timer不为NULL,则在timer指向的对象中也保存日期时间。

localtime 函数可以将 time_t类型的时间转换为 年 、月、日、时、分、秒等我们日常生活中使用的时间形式。

头文件

原型

说明

返回值

#include <time.h>

struct tm *localtime(const time_t *timer)

通过时间结构体类型将日期时间转换为相应的本地时间。

返回指向转换后时间的指针。

struct tm 结构体

#include <time.h>
/* 保存日期时间的时间结构体类型。 */
struct&nbsp;tm&nbsp;{
int&nbsp;tm_sec;&nbsp;&nbsp;&nbsp;&nbsp;// 秒 [0, 61]
int&nbsp;tm_min;&nbsp;&nbsp;&nbsp;&nbsp;// 分 [0, 59]
int&nbsp;tm_hour;&nbsp;&nbsp;&nbsp;// 时 [0, 23]
int&nbsp;tm_mday;&nbsp;&nbsp;&nbsp;//  日 [1, 31]
int&nbsp;tm_mon;&nbsp;&nbsp;&nbsp;&nbsp;// 距离1月份的月数  [0, 11]
int&nbsp;tm_year;&nbsp;&nbsp;&nbsp;//  距离 1900 年的年数
int&nbsp;tm_wday;&nbsp;&nbsp;// 距离星期日的天数  [0, 6]
int&nbsp;tm_yday;&nbsp;&nbsp;// 距离1月1日的天数  [0, 465]
int&nbsp;tm_isdst;&nbsp;&nbsp;&nbsp;// 夏令时
}

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

void&nbsp;put_date(void){
time_t&nbsp;current;
struct&nbsp;tm&nbsp;*local;
char&nbsp;wday_name[][7]&nbsp;=&nbsp;{&quot;&quot;,&nbsp;&quot;&quot;,&nbsp;&quot;&quot;,&nbsp;&quot;&quot;,&nbsp;&quot;&quot;,&nbsp;&quot;&quot;,&nbsp;&quot;&quot;};

time(&amp;current);
local&nbsp;=&nbsp;localtime(&amp;current);
printf(&quot;%4d年%02d月%02d日&nbsp;星期%s&nbsp;%02d:%02d:%02d&quot;,&nbsp;local-&gt;tm_year&nbsp;+&nbsp;1900,&nbsp;local-&gt;tm_mon&nbsp;+&nbsp;1,&nbsp;local-&gt;tm_mday,&nbsp;wday_name[local-&gt;tm_wday],&nbsp;local-&gt;tm_hour,&nbsp;local-&gt;tm_min,&nbsp;local-&gt;tm_sec);&nbsp;
}

int&nbsp;main(void){
printf(&quot;今天是&quot;);
put_date();
putchar(&#39;\n&#39;);

return&nbsp;0;
}

运行结果:
C 语言获取系统时间_2d

localtime 函数:从日历时间转换为分解时间

  1. localtime函数会返回转换后的 struct tm 类型对象的地址。
  2. 将其值转换为tm结构体类型的分解时间。
  3. 用公历表示分解时间。这时, tm_year + 1900,tm_mon + 1。由于星期日到星期六分别对应0到6,因此利用数组 wday_name 将表示星期的 tm_wday 转换为字符串年 、月、日、时、分、秒。

注:
转换后的 struct tm 类型对象已由localtime函数定义(在编写的程序中不能自行定义)。

举报

相关推荐

0 条评论