C#Datetimes:不同时区的转换 [英] C# Datetimes: Conversion for different time zones
问题描述
我有一堆日期时间,跟踪我的应用程序。他们都在UTC时间。对于我的一些应用程序,我想发送一封电子邮件,其中一个时间,但编辑为在特定的时区。
I have a bunch of date times that I keep track of for my app. They are all in UTC time. For part of my app I want to send an email with one of these times, but edited to be in that specific time zone.
我只有两个主要领域将处理东海岸和德克萨斯州(达拉斯和休斯顿)
There are only two major areas that I will deal with, the east coast and Texas (Dallas and Huston)
当我发送这封电子邮件以获得东部时区( DateTime timestamp = DateTime.Now;
)
I can also make a new datetime when I send out this email to get the eastern time zone (DateTime timestamp = DateTime.Now;
)
我的问题是这样的:
如果用户在德克萨斯地区,如何将我的时间从东部转换到那个时间(少于1小时)?
If the user is in the texas area how can I convert my time from eastern to that time (1 hour less)?
我尝试过这样的东西:
//Convert timestamp to local time
TimeSpan ts = TimeZone.CurrentTimeZone.GetUtcOffset(timestamp);
timestamp.Add(ts);
timestampString = timestamp.ToString();
但是没有工作。我也知道这一行无效:
But that didn't work. I also know that this line is not valid:
timestamp.Hour = timestamp.Hour - 1;
推荐答案
使用 TimeZoneInfo 将本地时间转换为替代时区的时间类:
Use the TimeZoneInfo Class to convert a local time to a time in an alternative timezone:
TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime targetTime = TimeZoneInfo.ConvertTime(timeToConvert, est);
这篇关于C#Datetimes:不同时区的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!