C# 日期时间:不同时区的转换 [英] C# Datetimes: Conversion for different time zones

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

问题描述

我有一堆日期时间可以跟踪我的应用程序.它们都是 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# 日期时间:不同时区的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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