繁体   English   中英

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

[英]How do I stop a date/time comparison from failing when a user is in a different time zone?

我正在获取可执行文件的“ 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()方法

暂无
暂无

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

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