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

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

问题描述

我有一大堆的日期时间,我跟踪我的应用程序。他们都在UTC时间。对于我的应用程序的一部分,我想这些时间之一发送电子邮件,但编辑要在特定的时区。

有两个主要的方面,我会处理,东海岸和得克萨斯州(达拉斯和休斯顿)

我也可以做一个新的日期时间,当我发送此电子邮件东部时区( DateTime时间戳= DateTime.Now;

我的问题是这样的:

如果用户是在德州地区我如何转换我的时间,从东部到时间(1小时以内)?

我想是这样的:

  //时间戳转换为本地时间
            时间跨度TS = TimeZone.CurrentTimeZone.GetUtcOffset(时间戳);
            timestamp.Add(TS);            timestampString = timestamp.ToString();

但没有奏效。我也知道,这条线是无效的:

  timestamp.Hour = timestamp.Hour  -  1;


解决方案

使用的TimeZoneInfo 类到本地时间转换为时间在替代时区:

 的TimeZoneInfo EST = TimeZoneInfo.FindSystemTimeZoneById(东部标准时间);
日期时间targetTime = TimeZoneInfo.ConvertTime(timeToConvert,EST);

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)

I can also make a new datetime when I send out this email to get the eastern time zone (DateTime timestamp = DateTime.Now;)

My Question is this:

If the user is in the texas area how can I convert my time from eastern to that time (1 hour less)?

I tried something like this:

            //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;

解决方案

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天全站免登陆