专业编程基础技术教程

网站首页 > 基础教程 正文

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

ccvgpt 2024-10-19 03:24:28 基础教程 8 ℃

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

struct tm *localtime(xonst time_t *timer)

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

该函数的作用是把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。


  1. tm_sec
  2. 分钟后的几秒 (0-59)。
  3. tm_min
  4. 小时后的分钟 (0-59)。
  5. tm_hour
  6. 午夜后经过的小时 (0-23)。
  7. tm_mday
  8. 月 (1-31) 天。
  9. tm_mon
  10. 月 (0 – 11;年 1 月 = 0)。
  11. tm_year
  12. 年份 (当前年份减去 1900年)。
  13. tm_wday
  14. 星期几 (0 – 6;星期日 = 0)。
  15. tm_yday
  16. 每年的一天 (0-365;1 月 1 日 = 0)。
  17. tm_isdst
  18. 如果夏令时有效,则为,正值夏时制不起作用; 如果为 0如果夏时制的状态是未知的负值。 如果 TZ 设置环境变量,C 运行库会假定规则适用于美国境内用于实现夏令时 (DST) 计算。

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


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

Tags:

最近发表
标签列表