C++ Reference: Standard C++ Library reference: C Library: ctime: asctime

发布于:2022-11-27 ⋅ 阅读:(357) ⋅ 点赞:(0)

C++官网参考链接:https://cplusplus.com/reference/ctime/asctime/

函数
<ctime>
asctime
char* asctime (const struct tm * timeptr);
将tm结构转换为字符串
将timeptr指向的tm结构的内容解释为日历时间,并将其转换为包含相应日期和时间的人类可读版本的C字符串。
返回的字符串格式如下: 
Www Mmm dd hh:mm:ss yyyy
其中Www是工作日,Mmm是月份(用字母表示),dd是月份的日期,hh:mm:ss是时间,yyyy是年份。
字符串后面跟着一个换行字符('\n'),并以空字符结束。
它的定义行为等价于:
char* asctime(const struct tm *timeptr)
{
  static const char wday_name[][4] = {
    "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
  };
  static const char mon_name[][4] = {
    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  };
  static char result[26];
  sprintf(result, "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n",
    wday_name[timeptr->tm_wday],
    mon_name[timeptr->tm_mon],
    timeptr->tm_mday, timeptr->tm_hour,
    timeptr->tm_min, timeptr->tm_sec,
    1900 + timeptr->tm_year);
  return result;
}
有关自定义日期格式的替代选项,请参阅strftime

形参 
timeptr
指向tm结构的指针,该结构 (参见struct tm)包含分解为其组件的日历时间。

返回值
一个C字符串,以人类可读的格式包含日期和时间信息。
返回值指向一个内部数组,其有效性或值可能被后续对asctime或ctime的调用所改变。 

用例
/* asctime example */
#include <stdio.h>      /* printf */
#include <time.h>       /* time_t, struct tm, time, localtime, asctime */

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;

  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  printf ( "The current date/time is: %s", asctime (timeinfo) );

  return 0;
}
输出:

数据竞争
该函数访问timeptr所指向的对象。
该函数还访问和修改共享内部缓冲区,这可能导致并发调用asctime或ctime时的数据竞争。有些库提供了避免这种数据竞争的替代函数:asctime_r(不可移植)。

异常(C++) 
无抛出保证:此函数从不抛出异常。 

另请参考
ctime    Convert time_t value to string (function)
gmtime    Convert time_t to tm as UTC time (function)
localtime    Convert time_t to tm as local time (function)
time    Get current time (function) 

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到