Ego*_*gor 1 .net c# timezone datetimeoffset .net-4.6
我有一个实例,考虑到夏令时规则DateTimeOffset,我需要在特定的TimeZone(西欧标准时间)中添加 1 天(因此它可能会导致Offset更改)。如果没有 3rd 方库,我该怎么做?
可验证示例:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestProject
{
[TestClass]
public class TimeZoneTests
{
[TestMethod]
public void DateTimeOffsetAddDays_DaylightSaving_OffsetChange()
{
var timeZoneId = "W. Europe Standard Time";
var utcTimestamp = new DateTimeOffset(2017, 10, 28, 22, 0, 0, TimeZoneInfo.Utc.BaseUtcOffset);
var weuropeStandardTimeTimestamp = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcTimestamp, timeZoneId);
Assert.AreEqual(new DateTime(2017, 10, 29), weuropeStandardTimeTimestamp.DateTime);
Assert.AreEqual(TimeSpan.FromHours(2), weuropeStandardTimeTimestamp.Offset);
var weuropeStandardTimeTimestampNextDay = AddDaysInTimeZone(weuropeStandardTimeTimestamp, 1, timeZoneId);
Assert.AreEqual(new DateTime(2017, 10, 30), weuropeStandardTimeTimestampNextDay);
Assert.AreEqual(TimeSpan.FromHours(1), weuropeStandardTimeTimestamp.Offset);
}
private DateTimeOffset AddDaysInTimeZone(DateTimeOffset timestamp, int days, string timeZoneId)
{
// this line has to be fixed:
return timestamp.AddDays(days);
}
}
}
Run Code Online (Sandbox Code Playgroud)
AddDaysInTimeZone 方法应替换为正确的实现。
PS 如果它导致无效/模棱两可/跳过日期,那么抛出异常是可以的。
TimeZoneInfo使这相当简单 - 只需DateTime在值的部分添加一天,检查结果是否被跳过或不明确,如果没有,请向区域询问 UTC 偏移量。这是一个完整的示例,显示了所有不同的可能性:
using System;
using System.Globalization;
using static System.FormattableString;
class Program
{
static void Main()
{
// Stay in winter
Test("2017-01-22T15:00:00+01:00");
// Skipped time during transition
Test("2017-03-25T02:30:00+01:00");
// Offset change to summer
Test("2017-03-25T15:00:00+01:00");
// Stay in summer
Test("2017-06-22T15:00:00+02:00");
// Ambiguous time during transition
Test("2017-10-28T02:30:00+02:00");
// Offset change back to winter
Test("2017-10-28T15:00:00+02:00");
// Stay in winter
Test("2017-12-22T15:00:00+01:00");
}
static void Test(string startText)
{
var zone = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
var start = DateTimeOffset.ParseExact(
startText, "yyyy-MM-dd'T'HH:mm:ssK", CultureInfo.InvariantCulture);
try
{
var end = AddOneDay(start, zone);
Console.WriteLine(Invariant($"{startText} => {end:yyyy-MM-dd'T'HH:mm:ssK}"));
}
catch (Exception e)
{
Console.WriteLine($"{startText} => {e.Message}");
}
}
static DateTimeOffset AddOneDay(DateTimeOffset start, TimeZoneInfo zone)
{
var newLocal = start.DateTime.AddDays(1);
// TODO: Use a better exception type :)
if (zone.IsAmbiguousTime(newLocal))
{
throw new Exception("Ambiguous");
}
if (zone.IsInvalidTime(newLocal))
{
throw new Exception("Skipped");
}
return new DateTimeOffset(newLocal, zone.GetUtcOffset(newLocal));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1424 次 |
| 最近记录: |