利用localtime_s函数格式化输出当地日期与时间

转载:https://blog.csdn.net/xingcen/article/details/55669054

Visual C++ 6.0开发环境中显示当地日期与时间主要通过localtime()函数来实现,该函数的原型在time.h头文件中,其语法格式如下:

1 struct tm *localtime(xonst time_t *timer)

该函数的作用是把timer所指的时间(如函数time返回的时间)转换为当地标准时间,并以tm结构形式返回。其中,参数timer为主要获取当前时间的传递参数,格式为time_t指针类型。

而在Visual Studio 2010极其以后的版本,新增了安全函数,改成localtime_s(),语法格式也发生了变化:

1 errno_t localtime_s(
2    struct tm* _tm,
3    const time_t *time 
4 );

其中:

1 _tm
2 指向要填充的时间结构的指针。
3 time
4 指针,指向存储的时间。

如果成功,返回值则为零。 如果失败,返回值将是错误代码。 错误代码是在 Errno.h 中定义的。

结构类型的字段 tm 存储下面的值,其中每个为 int。

tm_sec
分钟后的几秒 (0-59)。
tm_min
小时后的分钟 (0-59)。
tm_hour
午夜后经过的小时 (0-23)。
tm_mday
月 (1-31) 天。
tm_mon
月 (011;年 1 月 = 0)。
tm_year
年份 (当前年份减去 1900年)。
tm_wday
星期几 (06;星期日 = 0)。
tm_yday
每年的一天 (0-365;11 日 = 0)。
tm_isdst
如果夏令时有效,则为,正值夏时制不起作用; 如果为 0如果夏时制的状态是未知的负值。 如果 TZ 设置环境变量,C 运行库会假定规则适用于美国境内用于实

下面以一个实例来输出当地日期与时间:

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <time.h>
 4  
 5 int main(void)
 6 {
 7     struct tm t;   //tm结构指针
 8     time_t now;  //声明time_t类型变量
 9     time(&now);      //获取系统日期和时间
10     localtime_s(&t, &now);   //获取当地日期和时间
11         
12     //格式化输出本地时间
13     printf("年:%d
", t.tm_year + 1900);
14     printf("月:%d
", t.tm_mon + 1);
15     printf("日:%d
", t.tm_mday);
16     printf("周:%d
", t.tm_wday);
17     printf("一年中:%d
", t.tm_yday);
18     printf("时:%d
", t.tm_hour);
19     printf("分:%d
", t.tm_min);
20     printf("秒:%d
", t.tm_sec);
21     printf("夏令时:%d
", t.tm_isdst);
22     system("pause");
23     //getchar();
24     return 0;
25  
26 }
原文地址:https://www.cnblogs.com/Toya/p/14703602.html