格式化带偏移的日期 [英] Format A Date With Offset

查看:116
本文介绍了格式化带偏移的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Offset更改字符串DateTime值。这是我尝试过的过程,但最后,日期时间和datetime1打印其初始值。我想要的输出是将datetime1格式化为适当的Offset,以便其镜像datetime

I am attempting to alter a string DateTime value with Offset. This is the procedure I have attempted, but in the end, both datetime & datetime1 print their initial values. My desired output is to format datetime1 to the proper Offset so that it mirrors datetime


2016年1月10日5:18 PM

01/10/2016 5:18 PM-05:00

01/10/2016 5:18 PM
01/10/2016 5:18 PM-05:00



string datetime = "2017-01-10T17:18:00-05:00";
string datetime1 = "1/10/2016 3:18:00 PM";

DateTimeOffset dateTimeOffset = DateTimeOffset.Parse(datetime);
TimeSpan tspan = dateTimeOffset.Offset;
DateTimeOffset alteredDate = new     DateTimeOffset(Convert.ToDateTime(datetime1)).ToOffset(tspan);

UAB = Convert.ToString(DateTimeOffset.Parse(alteredDate.ToString()));

Console.WriteLine(datetime);
Console.WriteLine(UAB);
Console.ReadLine();

编辑

在浏览我的代码时,我注意到 tpsan 的值为 -05:00 可能会导致-符号是什么导致代码无法正确转换?

EDIT
When stepping through my code, I noticed that tpsan holds a value of -05:00 could the - sign be what is causing the code to not convert properly?

推荐答案

您收到的DateTimeOffset对象已经进行了调整

The DateTimeOffset object you receive is already adjusted for timezone.

string output = "";

// Parsing with explicit timezones
var withZeroOffset = DateTimeOffset.Parse("2017-01-10T17:18:00-00:00"); // parsed as UTC
var withOffset = DateTimeOffset.Parse("2017-01-10T17:18:00-05:00"); // Parsed as specific timezone
var withoutOffset = DateTimeOffset.Parse("2017-01-10T17:18:00"); // Parsed as my timezone
output += "All Times:\n" + withZeroOffset + "\n" + withOffset + "\n" + withoutOffset + "\n\n";

// Modifying timezones
var inputUtc = DateTimeOffset.Parse("2017-01-10T17:18:00Z").ToOffset(TimeSpan.Zero);
output += "Time UTC: " + inputUtc + "\n";
var minusFive = inputUtc.ToOffset(TimeSpan.FromHours(-5));
output += "Time @ -5:00: " + minusFive + "\n";
var myOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
var myTime = inputUtc.ToOffset(myOffset);
output += "Time in my timezone: (" + myOffset.TotalHours + ":00): " + myTime + "\n";

Console.WriteLine(output);

在我的机器上,带有我的时区,我得到以下输出:

On my machine, with my timezone, I get this output:

All Times:
1/10/2017 5:18:00 PM +00:00
1/10/2017 5:18:00 PM -05:00
1/10/2017 5:18:00 PM -08:00

Time UTC: 1/11/2017 1:18:00 AM +00:00
Time @ -5:00: 1/10/2017 8:18:00 PM -05:00
Time in my timezone: (-8:00): 1/10/2017 5:18:00 PM -08:00

我假设您的明确偏移量与您的实际时区匹配,这就是为什么您两次看到相同答案的原因。要显式更改DateTimeOffset对象的时区,请使用.ToOffset()。

I am assuming your explicit offset matches your actual timezone, which is why you see the same answer twice. To explicitly change the timezone of a DateTimeOffset object, use .ToOffset().

这篇关于格式化带偏移的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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