简体   繁体   English

了解 time_t 调用

[英]Understanding the time_t calls

I've written the following to print the local time as a string:我编写了以下内容以将本地时间打印为字符串:

 char time_buffer[25];
 time_t t = time(&t);
 strftime(time_buffer, 25, "%c", localtime(&t));
 printf("Formatted time: %s\n", time_buffer);

However, the code doesn't make too much sense to me (even though I've written it).但是,代码对我来说并没有太大意义(即使我已经编写了它)。 A few questions on it:关于它的几个问题:

  • How does time_t t = time(&t) work? time_t t = time(&t)是如何工作的? Is this setting up a struct of the localtime?这是设置本地时间的结构吗? Where is it grabbing the time from?它从哪里抢时间?
  • What is the difference between the time(&t) and localtime(&t) ? time(&t)localtime(&t)有什么区别? Why are both needed?为什么两者都需要?

time() is implemented in libc. time()在 libc 中实现。 For example, here is the implementation in glibc 2.33 for Linux:例如,下面是 glibc 2.33 中 Linux 的实现:

time (time_t *t)
{
  return INLINE_VSYSCALL (time, 1, t);
}

which asks the kernel via a syscall for the time.它通过系统调用询问 kernel 的时间。 The kernel, in turn, maintains a variable somewhere with this information.反过来,kernel 在某处使用此信息维护一个变量。 The kernel gets the time on boot from a battery backed clock and often subsequently sync'ed with a reference clock source (on Linux this would be via the Network Time Protocol (NTP)). kernel 从电池支持的时钟获取启动时间,然后通常与参考时钟源同步(在 Linux 上,这将通过网络时间协议 (NTP))。

time() returns a time_t (on my system that is a typedef of long) which is number of seconds since epoch (this is measure of time is independent of timezone). time()返回一个 time_t(在我的系统上是 long 的 typedef),它是自纪元以来的秒数(这是时间的度量,与时区无关)。 localtime() returns a struct tm * which has the usual components for of date and time (sec, min, hour, day, month, year etc) in whatever timezone you selected (on Linux via the environment variable TZ). localtime()返回一个struct tm * ,它在您选择的任何时区(通过环境变量 TZ 在 Linux 上)具有日期和时间(秒、分、小时、日、月、年等)的常用组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM