当用户处于不同的时区时,如何阻止日期/时间比较失败?

本文关键字:日期 何阻止 时间 比较 失败 用户 于不同 时区 | 更新日期: 2023-09-27 17:49:16

我正在获得我的可执行文件的"LastWriteTime",并将其与我设置的内部DateTime进行比较。如果LastWriteTime小于或等于内部DateTime,那么我将从数据库中清除两个表。

这段代码对我来说在太平洋时区工作得很好。但是,如果用户在另一个时区(例如比我早4小时),则它不起作用,因为"LastWriteTime"返回转换为他们时区的时间。例如,我正在寻找"12/12/2012 8:38:12 am"的值,如果他们比我早4小时,这个值在他们的系统上会自动更改为"12/12/2012 12:38:12 PM"。

有人能告诉我我应该在我的代码中修改什么,以考虑到不同的时区,所以"LastWriteTime"和我的"build2023_EXE_Date"变量都返回相同的日期/时间,所以我的两个日期/时间值的比较不会失败,不管我的最终用户在什么时区?

我用的是。net 3.5,不是。net 4.x

//http://stackoverflow.com/questions/1600962/displaying-the-build-date
string w_file = "MyEXE.exe";
string w_directory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
                       Path.DirectorySeparatorChar + "MyEXE";
DateTime currentExeTime = File.GetLastWriteTime(System.IO.Path.Combine(w_directory, w_file));

DateTime build2023_EXE_Date = new DateTime(2012, 12, 12, 8, 38, 12); //"12/12/2012 8:38:12 AM"
//We need to truncate the millisecond time off of the EXE LastWriteTime
//or else when we compare to our internal DateTime build2323_EXE_Date value,
//it will not match
//http://stackoverflow.com/questions/1004698/how-to-truncate-milliseconds-off-of-a-net-datetime
currentExeTime = new DateTime(
     currentExeTime.Ticks - (currentExeTime.Ticks % TimeSpan.TicksPerSecond),
            currentExeTime.Kind
            );
if (currentExeTime <= build2023_EXE_Date) //If previous build matches or is before the Build 2023 date then clear these two tables.
{
    //This will fail the comparision if the user is in a different time zone than me.
    //Clear tables
}

当用户处于不同的时区时,如何阻止日期/时间比较失败?

除非您有特殊需要以本地时间保存日期或有关联的时区,否则我建议您使用通用时间。这使得处理日期变得容易得多,因为它们都进行了合理的比较,并且实际上可以提高性能(当您请求DateTime.Now时,. net调用DateTime.UtcNow,然后执行相对昂贵的本地时间调整)。

另一个选择是使用DateTimeOffset,它存储一个带有偏移量的日期(而不是时区!)—例如,DST将给您不同的偏移量),并使比较像通用DateTime一样容易。然而,不幸的是,GetLastWriteTime不使用DateTimeOffset,所以这可能不适合您。

使用DateTime ToUniversalTime()方法