>我正在尝试使用偏移量更改字符串日期时间值。 这是我尝试过的过程,但最终,datetime和datetime1都打印了它们的初始值。 我想要的输出是将 datetime1 格式化为正确的偏移量,以便它镜像日期时间
2016/01/10 17
:18 2016/10/01 5:18 下午-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
-
符号是否会导致代码无法正确转换?
使用不同的构造函数:
DateTimeOffset alteredDate =
new DateTimeOffset( Convert.ToDateTime( datetime1 ), tspan );
以下是文档:
//
// Summary:
// Initializes a new instance of the System.DateTimeOffset structure using the specified
// System.DateTime value and offset.
//
// Parameters:
// dateTime:
// A date and time.
//
// offset:
// The time's offset from Coordinated Universal Time (UTC).
//
// Exceptions:
// T:System.ArgumentException:
// dateTime.Kind equals System.DateTimeKind.Utc and offset does not equal zero.-or-dateTime.Kind
// equals System.DateTimeKind.Local and offset does not equal the offset of the
// system's local time zone.-or-offset is not specified in whole minutes.
//
// T:System.ArgumentOutOfRangeException:
// offset is less than -14 hours or greater than 14 hours.-or-System.DateTimeOffset.UtcDateTime
// is less than System.DateTimeOffset.MinValue or greater than System.DateTimeOffset.MaxValue.
public DateTimeOffset(DateTime dateTime, TimeSpan offset);
您收到的 DateTimeOffset 对象已针对时区进行了调整。
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 + "nn";
// 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);
在我的机器上,使用我的时区,我得到以下输出:
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
我假设您的显式偏移量与您的实际时区匹配,这就是为什么您两次看到相同的答案的原因。 要显式更改日期时间偏移量对象的时区,请使用 。ToOffset()。