gpt4 book ai didi

c - 如何从 C 中的 gettimeofday 获取日期时间?

转载 作者:行者123 更新时间:2023-11-30 19:09:07 43 4
gpt4 key购买 nike

如何在 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得到系统当前的小时,同时得到分、秒和MS〜

最佳答案

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

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

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

避免使用像 60 这样的魔数(Magic Number)。 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

关于c - 如何从 C 中的 gettimeofday 获取日期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43732241/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com