【问题标题】:how to get datetime from gettimeofday in C?如何从 C 中的 gettimeofday 获取日期时间?
【发布时间】:2017-05-02 07:17:30
【问题描述】:

如何从 C 中的 gettimeofday 获取日期时间? 我需要将 tv.tv_sec 转换为 Hour:Minute:Second xx 没有 localtime 和 strftime 等功能......,只需通过计算得到它。例如 tv.tv_sec/60)%60 将是分钟

#include <stdio.h>
#include <time.h>
#include<sys/time.h>

int main ()
{
  struct  timeval tv;
  struct  timezone   tz;
  gettimeofday(&tv,&tz);
  printf("TimeZone-1=%d\n", tz.tz_minuteswest);
  printf("TimeZone-2=%d\n", tz.tz_dsttime);
  printf("TimeVal-3=%d\n", tv.tv_sec);
  printf("TimeVal-4=%d\n", tv.tv_usec);
  printf ( "Current local time and date: %d-%d\n", (tv.tv_sec%    (24*60*60)/3600,tz.tz_minuteswest);

    return 0;
  }

如何通过计算 tv 和 tz 来获取系统当前的 Hour,以及获取 Minute、Second 和 MS ~

【问题讨论】:

标签: c gettimeofday


【解决方案1】:

假设:time_t 是一天开始后的秒数 - 通用时间。这通常是 1970 年 1 月 1 日 UTC,其中代码假定使用给定 sys/time.h

主要思想是从tv,tz的每个成员中提取数据形成本地时间。时间,UTC,从 tv.tv_sec 开始的秒数,从时区偏移和每个 DST 标志的小时调整的分钟数。最后,确保结果在主要范围内。

各种类型问题包括tv 的字段未指定为int

避免使用像60 这样的幻数。 SEC_PER_MIN 自行记录代码。

#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#define SEC_PER_DAY   86400
#define SEC_PER_HOUR  3600
#define SEC_PER_MIN   60

int main() {
  struct timeval tv;
  struct timezone tz;
  gettimeofday(&tv, &tz);
  printf("TimeZone-1 = %d\n", tz.tz_minuteswest);
  printf("TimeZone-2 = %d\n", tz.tz_dsttime);
  // Cast members as specific type of the members may be various 
  // signed integer types with Unix.
  printf("TimeVal-3  = %lld\n", (long long) tv.tv_sec);
  printf("TimeVal-4  = %lld\n", (long long) tv.tv_usec);

  // Form the seconds of the day
  long hms = tv.tv_sec % SEC_PER_DAY;
  hms += tz.tz_dsttime * SEC_PER_HOUR;
  hms -= tz.tz_minuteswest * SEC_PER_MIN;
  // mod `hms` to insure in positive range of [0...SEC_PER_DAY)
  hms = (hms + SEC_PER_DAY) % SEC_PER_DAY;

  // Tear apart hms into h:m:s
  int hour = hms / SEC_PER_HOUR;
  int min = (hms % SEC_PER_HOUR) / SEC_PER_MIN;
  int sec = (hms % SEC_PER_HOUR) % SEC_PER_MIN; // or hms % SEC_PER_MIN

  printf("Current local time: %d:%02d:%02d\n", hour, min, sec);
  return 0;
}

输出样本

TimeZone-1 = 360
TimeZone-2 = 1
TimeVal-3  = 1493735463
TimeVal-4  = 525199
Current local time: 9:31:03

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-04
  • 2011-02-20
  • 2013-12-09
相关资源
最近更新 更多