将日期时间转换为另一个时区 [英] Convert DateTime to another timezone
问题描述
如何将 DateTime
从 DateTime.Now
返回的本地时区转换为 Utc 以外的其他时区.在桌面上,我们有 TimeZoneInfo.ConvertTimeBySystemTimeZoneId()
,但它在 Windows 手机上不可用!
How do I convert a DateTime
from the local timezone returned by DateTime.Now
to another timezone than Utc. On desktop we have the TimeZoneInfo.ConvertTimeBySystemTimeZoneId()
, but it's not available on windows phone!
这个java片段大致显示了我想要做什么
This java snippet shows roughtly what I want to do
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
TimeZone tz = TimeZone.getDefault();
format.setTimeZone(TimeZone.getTimeZone("GMT"));
str = format.format(new Date());
推荐答案
使用系统库无法做到这一点,因为除了 local 和 utc 之外,无法创建 TimeZoneInfo
对象.他们还密封了课程.
This is not possible to do using the system libraries as there is no way to create TimeZoneInfo
objects other than local and utc. They have also sealed the class.
然而,您可以使用这个简单的库来启用到非本地时区的转换.https://nuget.org/packages/WinRTTimeZones
You can however use this simple library to enable conversion to non-local time zones. https://nuget.org/packages/WinRTTimeZones
像这样使用它:
using TimeZones;
public void ConvertTime()
{
// Get the time zone we want
var tz = TimeZoneService.FindSystemTimeZoneById("Central Standard Time");
var dt = new DateTime(1990, 7, 1, 12, 0, 0, DateTimeKind.Utc);
// This time will be central time
var local = tz.ConvertTime(dt);
}
当 DateTime
被转换后,根据需要对其进行格式化是一项简单的练习.我建议以本地格式(而不是本地时区)格式化日期,以便用户理解日期.
When the DateTime
is converted it is an easy exercise to format it as you want. I recommend to format the date in the local format (not the local timezone) to make easy for the user to understand the date.
这篇关于将日期时间转换为另一个时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!