我的应用程序以UTC获取DateTime对象,并需要以EST格式将其输出为字符串。我已经尝试了以下代码,但是当我得到输出时,偏移量仍显示为+00:00而不是-05:00
static void Main(string[] args)
{
var currentDate = DateTime.Now.ToUniversalTime();
var convertedTime = ConvertUtcToEasternStandard(currentDate);
Console.WriteLine(currentDate.ToString("yyyy-MM-ddTHH:mm:sszzz"));
Console.WriteLine(convertedTime.ToString("yyyy-MM-ddTHH:mm:sszzz"));
}
private static DateTime ConvertUtcToEasternStandard(DateTime dateTime)
{
var easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
return TimeZoneInfo.ConvertTimeFromUtc(dateTime, easternZone);
}
输出:
2016-11-18T06:56:14+00:00
2016-11-18T01:56:14+00:00
因此,时间已正确偏移,但当我希望偏移量为-05:00时,偏移量保持在+00:00。知道在使用上述格式字符串输出时如何获取具有正确偏移量的DateTime对象吗?
我基本上是不久前在API中阅读的,基本上,有了DateTime
值,很难获得zzz
有用的格式偏移量。
使用DateTime值,“ zzz”自定义格式说明符表示本地操作系统时区相对UTC的带符号偏移,以小时和分钟为单位。它不反映实例的DateTime.Kind属性的值。因此,不建议将“ zzz”格式说明符与DateTime值一起使用。
使用DateTimeOffset值,此格式说明符以小时和分钟为单位表示DateTimeOffset值与UTC的偏移量。
偏移量始终以前导符号显示。加号(+)表示UTC之前的小时,减号(-)表示UTC之前的小时。单位偏移量的格式为前导零。
例如,我在美国东部标准时间,这是我的结果:
2016-11-18T07:9:38-05:00
2016-11-18T02:9:38-05:00
显然,UTC时间不应具有的偏移量-05:00
。
稍微修改您的代码,我们有一个解决方案:
void Main()
{
var currentDate = DateTimeOffset.Now.ToUniversalTime();
var convertedTime = ConvertUtcToEasternStandard(currentDate);
var format = "yyyy-MM-ddTHH:m:sszzz";
Console.WriteLine(currentDate.ToString(format));
Console.WriteLine(convertedTime.ToString(format));
}
// Define other methods and classes here
private static DateTimeOffset ConvertUtcToEasternStandard(DateTimeOffset dateTime)
{
var easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
return TimeZoneInfo.ConvertTime(dateTime, easternZone);
}
结果:
2016-11-18T07:17:46+00:00
2016-11-18T02:17:46-05:00
这还差不多。
注意:取代了以前的代码,无知使我受益匪浅,但我没意识到这是行不通的。TimeZoneInfo.ConvertTime
需要一个DateTimeOffset
我们想要的东西。
如果我们为加上另一种情况Pacific Standard Time
:
private static DateTimeOffset ConvertUtcToPacificStandard(DateTimeOffset dateTime)
{
var pacificZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
return TimeZoneInfo.ConvertTime(dateTime, pacificZone);
}
我们得到正确的结果:
2016-11-17T23:21:21-08:00
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句