C语言关于localtime_s()和asctime_s()两个函数的用法

请问一下 你的这个问题最后是怎么解决的。我现在用vs2013第一次写带有时间的代码,也碰到说localtime_s未初始化的现象 求教解决方法。

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

struct tm *localtime(xonst time_t *timer)

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

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


errno_t localtime_s(
   struct tm* _tm,
   const time_t *time 
);

其中:

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

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

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

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

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

#include <iostream>
#include <ctime>
 
using namespace std;
 
int main(void)
{
    struct tm t;    //tm结构指针
    time_t now;     //声明time_t类型变量
    time(&now);     //获取系统日期和时间
    localtime_s(&t, &now);   //获取当地日期和时间
         
    //格式化输出本地时间
    printf("年:%d\n", t.tm_year + 1900);
    printf("月:%d\n", t.tm_mon + 1);
    printf("日:%d\n", t.tm_mday);
    printf("周:%d\n", t.tm_wday);
    printf("一年中的第%d天\n", t.tm_yday);
    printf("时:%d\n", t.tm_hour);
    printf("分:%d\n", t.tm_min);
    printf("秒:%d\n", t.tm_sec);
    printf("夏令时:%d\n", t.tm_isdst);
    system("pause");
    return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-09-08
#include <stdio.h>
#include <time.h>

#define TIME_MAX 32

void get_time(void);

int main()
{
  get_time();
  getchar();
  return 0;
}

void get_time(void)
{
  time_t now;
  time(&now);

  // 定义两个变量,存储转换结果
  struct tm tmTmp;
  char stTmp[TIME_MAX];

  // 转换为tm结构
  localtime_s(&tmTmp,&now);

  // 转换为字符串并输出
  asctime_s(stTmp,&tmTmp);
  printf("Current time is: %s\n",stTmp);
}

本回答被提问者和网友采纳
相似回答