-1

如何从 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~

4

1 回答 1

2

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

主要思想是从每个成员中提取tv,tz数据以形成本地时间。Time-of-day ,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
于 2017-05-02T14:31:39.803 回答