在C#3.5 FX创建在一个特定的时区的日期时间 [英] Creating a DateTime in a specific Time Zone in c# fx 3.5

查看:192
本文介绍了在C#3.5 FX创建在一个特定的时区的日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个单元测试来测试时,一台机器上的时区的变化,因为它已被错误设置,然后校正的情况。

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.

在测试我需要能够在一个没有本地时区创建日期时间的对象,以确保运行测试的人可以做这样成功地不论它们位于何处。

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构造我可以设置时区看到是本地时区的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?

推荐答案

<一个href="http://stackoverflow.com/questions/246498/creating-a-datetime-in-a-specific-time-zone-in-c-fx-35#246512">Jon's回答有关时区的谈判,但我建议使用的的TimeZoneInfo 代替。

Jon's answer talks about TimeZone, but I'd suggest using TimeZoneInfo instead.

我个人更喜欢保持事情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)
    {
        utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTime, 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); 
        }
    }        
}

您可能希望改变时区名的TimeZoneInfo为了让事情更清楚 - 我preFER了简短的名字我自己

You may wish to change the "TimeZone" names to "TimeZoneInfo" to make things clearer - I prefer the briefer names myself.

这篇关于在C#3.5 FX创建在一个特定的时区的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆