在c#fx 3.5中的特定时区创建DateTime [英] Creating a DateTime in a specific Time Zone in c# fx 3.5
问题描述
我正在尝试创建一个单元测试,以测试机器上的时区如何更改,然后更正的情况。
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一个特定的时区如PST?
How do I create a DateTime with a specific timezone like PST?
推荐答案
谈论我们/ library / system.timezone.aspxrel =nofollow noreferrer> TimeZone ,但我建议使用 TimeZoneInfo 。
个人而言,我喜欢在UTC的时候尽可能的保留东西,所以我建议一个这样的结构:
Personally I like keeping things in UTC where possible, 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#fx 3.5中的特定时区创建DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!