将时钟时间(真实世界时间)转换为 jiffies,反之亦然
Converting clock time (real world time) to jiffies and vice versa
我使用 mktime64
将时钟时间转换为 jiffies 值。
// year, mon, day, hour, min, sec
unsigned long my_jiffies = mktime64(2020, 2, 24, 3, 2, 50);
以上代码的输出是:1582513370
- 如何将该 jiffies 值转换回时钟时间?
[这个答案是针对 Linux 内核的,因为 linux-kernel 在问题中被标记了。]
mktime64
与 jiffies 无关。它将参数指定的日期转换为自 1970 年 1 月 1 日以来的秒数(忽略闰秒)00:00:00(如果参数用于 GMT,则为纪元以来的 Unix 时间)。
返回的time64_t
值可以通过内核中的time64_to_tm
函数转换回年、月、日、时、分、秒。它有这个原型:
void time64_to_tm(time64_t totalsecs, int offset, struct tm *result);
offset
参数是以秒为单位的本地时区偏移量(格林威治标准时间以东的秒数)。应将其设置为 0 以撤消 mktime64
.
完成的转换
请注意,tm_year
成员设置为计算年份减 1900,tm_mon
成员设置为计算月份减 1,因此您可以实现 unmktime64
函数如下:
void unmktime64(time64_t totalsecs,
int *year, unsigned int *month, unsigned int *day,
unsigned int *hour, unsigned int *minute, unsigned int *second)
{
struct tm tm;
time64_to_tm(totalsecs, 0, &tm);
*year = tm.tm_year + 1900;
*month = tm.tm_mon + 1;
*day = tm.tm_mday;
*hour = tm.tm_hour;
*minute = tm.tm_min;
*second = tm.tm_sec;
}
我使用 mktime64
将时钟时间转换为 jiffies 值。
// year, mon, day, hour, min, sec
unsigned long my_jiffies = mktime64(2020, 2, 24, 3, 2, 50);
以上代码的输出是:1582513370
- 如何将该 jiffies 值转换回时钟时间?
[这个答案是针对 Linux 内核的,因为 linux-kernel 在问题中被标记了。]
mktime64
与 jiffies 无关。它将参数指定的日期转换为自 1970 年 1 月 1 日以来的秒数(忽略闰秒)00:00:00(如果参数用于 GMT,则为纪元以来的 Unix 时间)。
返回的time64_t
值可以通过内核中的time64_to_tm
函数转换回年、月、日、时、分、秒。它有这个原型:
void time64_to_tm(time64_t totalsecs, int offset, struct tm *result);
offset
参数是以秒为单位的本地时区偏移量(格林威治标准时间以东的秒数)。应将其设置为 0 以撤消 mktime64
.
请注意,tm_year
成员设置为计算年份减 1900,tm_mon
成员设置为计算月份减 1,因此您可以实现 unmktime64
函数如下:
void unmktime64(time64_t totalsecs,
int *year, unsigned int *month, unsigned int *day,
unsigned int *hour, unsigned int *minute, unsigned int *second)
{
struct tm tm;
time64_to_tm(totalsecs, 0, &tm);
*year = tm.tm_year + 1900;
*month = tm.tm_mon + 1;
*day = tm.tm_mday;
*hour = tm.tm_hour;
*minute = tm.tm_min;
*second = tm.tm_sec;
}