在 c# 中的特定时区中创建日期时间 [英] Creating a DateTime in a specific Time Zone in c#

查看:56
本文介绍了在 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.

如何创建具有特定时区(如 PST)的 DateTime?

How do I create a DateTime with a specific timezone like PST?

推荐答案

Jon 的回答 谈到了 TimeZone,但我建议使用 TimeZoneInfo 代替.

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# 中的特定时区中创建日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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