Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

แปลงเวลาไฟล์ Windows เป็นเวลาท้องถิ่นใน C#

ภาพรวม

เมธอด DateTimeOffset.FromFileTime(long) แปลงค่าเวลาไฟล์ Windows (Windows file time - จำนวนทิก 100 นาโนวินาที นับจาก 1 มกราคม 1601 UTC) เป็น DateTimeOffset แสดงเวลาท้องถิ่น (local time) ของระบบ

ตัวอย่างที่ 1: แปลงค่า 0 (epoch ของ Windows file time)

using System;

public class Demo
{
    public static void Main()
    {
        DateTimeOffset offset = DateTimeOffset.FromFileTime(0);
        Console.WriteLine("DateTimeOffset = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", offset);
    }
}

ผลลัพธ์

DateTimeOffset = 01 January 1601, 12:00:00

ตัวอย่างที่ 2: แปลงค่า 200,000,000 ทิก

using System;

public class Demo
{
    public static void Main()
    {
        DateTimeOffset offset = DateTimeOffset.FromFileTime(200000000);
        Console.WriteLine("DateTimeOffset = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", offset);
    }
}

ผลลัพธ์

DateTimeOffset = 01 January 1601, 12:00:20

คำอธิบายเพิ่มเติม

  • Windows file time เริ่มนับจาก 1 มกราคม 1601 00:00:00 UTC (ต่างจาก Unix epoch ที่เริ่ม 1970)
  • 1 tick = 100 นาโนวินาที = 0.0001 มิลลิวินาที 10,000,000 ticks = 1 วินาที
  • DateTimeOffset เก็บข้อมูล offset จาก UTC ไว้ด้วย เหมาะสำหรับการแปลงเขตเวลา
  • เมธอดที่เกี่ยวข้อง: DateTime.FromFileTime() (คืน DateTime), DateTimeOffset.ToFileTime() (แปลงกลับ)
  • ใช้ในการอ่าน metadata ไฟล์ (creation time, last write time) จากระบบไฟล์ Windows