C#:确保DateTime.Now返回GMT + 1次

And*_*ech 11 c# timezone datetime

DateTime.Now用来根据今天的日期显示一些东西,当在当地工作(马耳他,欧洲)时,时间显示正确(显然是因为时区)但当我将其上传到我的托管服务器(美国)时,DateTime.Now并不代表正确的时区.

因此,在我的代码中,如何转换DateTime.Now为正确返回GMT + 1时区的时间

Llo*_*ell 16

使用System.Core中的TimeZoneInfo类;

您必须将DateTimeKind设置为DateTimeKind.Utc.

DateTime MyTime = new DateTime(1990, 12, 02, 19, 31, 30, DateTimeKind.Utc);

DateTime MyTimeInWesternEurope = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(MyTime, "W. Europe Standard Time");
Run Code Online (Sandbox Code Playgroud)

只有当你使用.Net 3.5时!


Jon*_*eet 15

这取决于你所说的"GMT + 1时区".您是指永久UTC + 1,还是指UTC + 1或UTC + 2,具体取决于DST?

如果您使用的是.NET 3.5,请使用TimeZoneInfo以获取适当的时区,然后使用:

// Store this statically somewhere
TimeZoneInfo maltaTimeZone = TimeZoneInfo.FindSystemTimeZoneById("...");
DateTime utc = DateTime.UtcNow;
DateTime malta = TimeZoneInfo.ConvertTimeFromUtc(utc, maltaTimeZone );
Run Code Online (Sandbox Code Playgroud)

您需要计算出马耳他时区的系统ID,但您可以通过在本地运行此代码轻松完成此操作:

Console.WriteLine(TimeZoneInfo.Local.Id);
Run Code Online (Sandbox Code Playgroud)

从您的评论来看,这一点将无关紧要,但仅限于其他人......

如果您使用.NET 3.5,则需要自己计算夏令时.说实话,最简单的方法是成为一个简单的查找表.计算出未来几年的DST变化,然后编写一个简单的方法,在特定的UTC时间返回偏移量,并对该列表进行硬编码.您可能只想要List<DateTime>使用已知更改进行排序,并在您的日期在最后一次更改之后交替使用1到2小时:

// Be very careful when building this list, and make sure they're UTC times!
private static readonly IEnumerable<DateTime> DstChanges = ...;

static DateTime ConvertToLocalTime(DateTime utc)
{
    int hours = 1; // Or 2, depending on the first entry in your list
    foreach (DateTime dstChange in DstChanges)
    {
        if (utc < dstChange)
        {
            return DateTime.SpecifyKind(utc.AddHours(hours), DateTimeKind.Local);
        }
        hours = 3 - hours; // Alternate between 1 and 2
    }
    throw new ArgumentOutOfRangeException("I don't have enough DST data!");
}
Run Code Online (Sandbox Code Playgroud)


Fre*_*örk 5

我不认为您可以在代码中设置一个属性以使DateTime.Now返回除执行代码的计算机的当前时间以外的任何内容。如果您希望始终获得其他时间,则可能需要包装其他函数。您可以在UTC上进行往返,并添加所需的偏移量:

private static DateTime GetMyTime()
{
    return DateTime.UtcNow.AddHours(1);
}
Run Code Online (Sandbox Code Playgroud)

(代码示例在卢克对DateTime.Now的内部工作原理发表评论后更新)