Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Chuyển DateTime sang Windows File Time trong C#

Mục đích

Phương thức DateTime.ToFileTime() chuyển giá trị DateTime sang **Windows File Time**: số tick 100-nanosecond từ 00:00:00 ngày 1/1/1601 (UTC). Dùng cho hệ thống file, registry, Win32 API.

Ví dụ 1: Thời gian hiện tại

using System;

public class Demo
{
    public static void Main()
    {
        DateTime now = DateTime.Now;
        Console.WriteLine($"Local time: {now}");

        long fileTime = now.ToFileTime(); // Chuyển sang UTC rồi tính tick
        Console.WriteLine($"Windows File Time: {fileTime}");

        // Ngược lại: từ FileTime về DateTime
        DateTime restored = DateTime.FromFileTime(fileTime);
        Console.WriteLine($"Restored (Local): {restored}");
    }
}

Kết quả (ví dụ)

Local time: 10/16/2019 8:17:26 AM
Windows File Time: 132156874462559390
Restored (Local): 10/16/2019 8:17:26 AM

Ví dụ 2: DateTime cụ thể

using System;

public class Demo
{
    public static void Main()
    {
        DateTime dt = new DateTime(2019, 5, 10, 6, 10, 25); // Local time
        Console.WriteLine($"DateTime: {dt}");

        long ft = dt.ToFileTime();
        Console.WriteLine($"File Time: {ft}");

        // Kiểm tra round-trip
        DateTime dt2 = DateTime.FromFileTime(ft);
        Console.WriteLine($"Round-trip: {dt2} (Kind: {dt2.Kind})");
    }
}

Kết quả

DateTime: 5/10/2019 6:10:25 AM
File Time: 132019422250000000
Round-trip: 5/10/2019 6:10:25 AM (Kind: Local)

Lưu ý quan trọng

  • ToFileTime() giả định DateTime.Kind là Local hoặc Unspecified -> chuyển sang UTC trước khi tính tick.
  • Nếu Kind = Utc, dùng ToFileTimeUtc() (không chuyển đổi múi giờ).
  • Phạm vi: 1/1/1601 đến ~ năm 30828 (Int64.MaxValue ticks).
  • Độ phân giải: 100 nanosecond (1 tick = 0.1 microsecond).

So sánh với Unix Timestamp

Đặc điểmWindows File TimeUnix Timestamp
Epoch1/1/1601 UTC1/1/1970 UTC
Đơn vị100 ns (tick)Giây (thường)
Kiểu dữ liệuInt64Int32/Int64
Dùng choWindows API, NTFS, RegistryLinux, Web, Cross-platform

Chuyển đổi sang Unix Timestamp

public static long ToUnixTimeSeconds(DateTime dt)
{
    DateTimeOffset dto = dt.Kind == DateTimeKind.Utc ? new DateTimeOffset(dt) : new DateTimeOffset(dt.ToUniversalTime());
    return dto.ToUnixTimeSeconds();
}