在C#中的特定时区中创建DateTime [英] Creating a DateTime in a specific Time Zone in c#
问题描述
我正在尝试创建一个单元测试,以测试由于未正确设置然后更正时区而在计算机上更改时区的情况。
I'm trying to create a unit test to test the case for when the timezone changes on a machine because it has been incorrectly set and then corrected.
在测试中,我需要能够在一个非本地时区中创建DateTime对象,以确保运行该测试的人可以成功地进行操作,而不管他们位于何处。
In the test I need to be able to create DateTime objects in a none local time zone to ensure that people running the test can do so successfully irrespective of where they are located.
从DateTime构造函数中可以看到,我可以将TimeZone设置为本地时区,UTC时区或未指定。
From what I can see from the DateTime constructor I can set the TimeZone to be either the local timezone, the UTC timezone or not specified.
如何使用以下方式创建DateTime
How do I create a DateTime with a specific timezone like PST?
推荐答案
Jon's answer talks about TimeZone, but I'd suggest using TimeZoneInfo instead.
我个人希望尽可能将内容保留在UTC中(至少在过去; 为未来存储UTC 有潜在的问题),所以我建议采用这样的结构:
Personally I like keeping things in UTC where possible (at least for the past; storing UTC for the future has potential issues), so I'd suggest a structure like this:
public struct DateTimeWithZone
{
private readonly DateTime utcDateTime;
private readonly TimeZoneInfo timeZone;
public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone)
{
var dateTimeUnspec = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);
utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTimeUnspec, timeZone);
this.timeZone = timeZone;
}
public DateTime UniversalTime { get { return utcDateTime; } }
public TimeZoneInfo TimeZone { get { return timeZone; } }
public DateTime LocalTime
{
get
{
return TimeZoneInfo.ConvertTime(utcDateTime, timeZone);
}
}
}
您可能希望更改将 TimeZone命名为 TimeZoneInfo,以便使事情更清楚-我更喜欢由简报者命名。
You may wish to change the "TimeZone" names to "TimeZoneInfo" to make things clearer - I prefer the briefer names myself.
这篇关于在C#中的特定时区中创建DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!