如何将 unsigned long long 类型的刻度转换为可读时间格式?

How to convert ticks in unsigned long long type to readable time format?

我必须为 Linux 编写一个内核模块,它写入所有进程的启动时间。 我使用 struct task_struct 获取有关进程的信息。

struct task_struct *task = get_current();
struct task_struct *head;
struct list_head *current_list;


struct rtc_time time;
list_for_each(current_list, &task->tasks)
{
    head = list_entry(current_list, struct task_struct, tasks);

    rtc_time64_to_tm(head->se.exec_start, &time);
    printk(KERN_INFO "%d:%d:%d %d/%d/%d", time.tm_hour, time.tm_min, time.tm_sec, 
        time.tm_year, time.tm_mon, time.tm_yday);
}

rtc_time64_to_tm() 采用参数 long long,但 head->se.exec_start 具有类型 unsigned long long。这就是我无法将其转换为可读时间格式的原因。

// Convert seconds since 01-01-1970 00:00:00 to Gregorian date.

void rtc_time64_to_tm(time64_t time, struct rtc_time *tm)

如果代码确实需要显示未来的日期,请利用 YMD HMS 模式每 400 年重复一次的优势。

#define SEC_PER400YEAR (60LL*60*24*(365L*400+97))

unsigned long long start = head->se.exec_start;
unsigned long long year = 0;
if (start > LLONG_MAX) {
  year = (start/SEC_PER400YEAR)*400;
  start %= SEC_PER400YEAR;
}
rtc_time64_to_tm((long long) start, &time);

printk(KERN_INFO "%lld/%d/%d", time.tm_year +year, time.tm_mon, time.tm_yday);

IMO,start 的值超过 LLONG_MAX 是可疑的。

注意:if (start > LLONG_MAX)并非真正需要。

如果关注 TZ、DST,该方法需要稍微 mod。