简体   繁体   English

将FILETIME转换为可移植的时间单位

[英]Convert FILETIME to portable time unit

How would I go about converting a Windows FILETIME object into a time_t or raw seconds/milliseconds? 如何将Windows FILETIME对象转换为time_t或原始秒/毫秒? I'm porting some code from Windows to Unix so I cannot rely on the Windows API functions. 我正在将一些代码从Windows移植到Unix,所以我不能依赖Windows API函数。

A FILETIME is defined as FILETIME定义为

Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC). 包含一个64位值,代表自1601年1月1日(UTC)起100纳秒间隔的数量。

So to convert it to a Unix time, it's just a matter of subtracting the two epoch times and converting from 100-nanosecond intervals to seconds/millisconds. 因此,要将其转换为Unix时间,只需减去两个纪元时间并将100纳秒的间隔转换为秒/毫粘滞。 Any number of tools/sites will tell you that the two epochs are 134774 days (or 11644473600 seconds) apart. 任何数量的工具/站点都将告诉您两个纪元相隔134774天(或11644473600秒)。 Therefore: 因此:

void convert_filetime(struct timeval *out_tv, const FILETIME *filetime)
{
    // Microseconds between 1601-01-01 00:00:00 UTC and 1970-01-01 00:00:00 UTC
    static const uint64_t EPOCH_DIFFERENCE_MICROS = 11644473600000000ull;

    // First convert 100-ns intervals to microseconds, then adjust for the
    // epoch difference
    uint64_t total_us = (((uint64_t)filetime->dwHighDateTime << 32) | (uint64_t)filetime->dwLowDateTime) / 10;
    total_us -= EPOCH_DIFFERENCE_MICROS;

    // Convert to (seconds, microseconds)
    out_tv->tv_sec = (time_t)(total_us / 1000000);
    out_tv->tv_usec = (useconds_t)(total_us % 1000000);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM