我正在尝试创建一个单元测试来测试在机器上因错误设置后又进行了更正导致时区发生变化的情况。
在测试中,我需要能够创建非本地时区的DateTime对象,以确保无论用户位于何处都可以成功运行测试。
从DateTime构造函数中可以看到,TimeZone可以设置为本地时区、UTC时区或不指定。
如何创建具有特定时区(例如PST)的DateTime?
我正在尝试创建一个单元测试来测试在机器上因错误设置后又进行了更正导致时区发生变化的情况。
在测试中,我需要能够创建非本地时区的DateTime对象,以确保无论用户位于何处都可以成功运行测试。
从DateTime构造函数中可以看到,TimeZone可以设置为本地时区、UTC时区或不指定。
如何创建具有特定时区(例如PST)的DateTime?
Jon的回答提到了 TimeZone,但我建议使用TimeZoneInfo。
个人来说,在可能的情况下(至少对于过去的时间而言;存储未来的UTC存在潜在问题),我喜欢将事物保留在UTC中,因此我建议使用以下结构:
public struct DateTimeWithZone
{
private readonly DateTime utcDateTime;
private readonly TimeZoneInfo timeZone;
public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone)
{
var dateTimeUnspec = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);
utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTimeUnspec, timeZone);
this.timeZone = timeZone;
}
public DateTime UniversalTime { get { return utcDateTime; } }
public TimeZoneInfo TimeZone { get { return timeZone; } }
public DateTime LocalTime
{
get
{
return TimeZoneInfo.ConvertTime(utcDateTime, timeZone);
}
}
}
您可能希望将“TimeZone”更改为“TimeZoneInfo”,以使事情更清晰 - 我个人更喜欢简短的名称。
DateTimeOffset结构是专门为这种类型的使用而创建的。
参见: http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx
下面是一个使用特定时区创建DateTimeOffset对象的示例:
DateTimeOffset do1 = new DateTimeOffset(2008, 8, 22, 1, 0, 0, new TimeSpan(-5, 0, 0));
这里的其他回答很有用,但它们没有涵盖如何访问太平洋时区 - 下面是方法:
public static DateTime GmtToPacific(DateTime dateTime)
{
return TimeZoneInfo.ConvertTimeFromUtc(dateTime,
TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"));
}
奇怪的是,尽管“太平洋标准时间”通常意味着与“太平洋夏令时间”有所不同,但在这种情况下,它指的是太平洋时间。实际上,如果您使用 FindSystemTimeZoneById
获取它,其中一个可用的属性是一个布尔值,告诉您该时区当前是否处于夏令时。
您可以在我最终放弃组合处理DateTime的库中看到更广泛的示例,具体取决于用户的提问位置和不同的TimeZone:
https://github.com/b9chris/TimeZoneInfoLib.Net
这在Windows之外是行不通的(例如Linux上的Mono),因为时间列表来自Windows Registry:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\
在此之下,您将找到键(Registry Editor中的文件夹图标);这些键的名称就是您要传递给 FindSystemTimeZoneById
的参数。在Linux上,您必须使用一组独立的Linux标准时区定义,但我尚未充分探讨。
我稍微改变了Jon Skeet的答案,使用扩展方法适用于网络。它在Azure上也运行得很好。
public static class DateTimeWithZone
{
private static readonly TimeZoneInfo timeZone;
static DateTimeWithZone()
{
//I added web.config <add key="CurrentTimeZoneId" value="Central Europe Standard Time" />
//You can add value directly into function.
timeZone = TimeZoneInfo.FindSystemTimeZoneById(ConfigurationManager.AppSettings["CurrentTimeZoneId"]);
}
public static DateTime LocalTime(this DateTime t)
{
return TimeZoneInfo.ConvertTime(t, timeZone);
}
}
public DateTime TimeInOriginalZone { get { return TimeZoneInfo.ConvertTime(utcDateTime, timeZone); } }
public DateTime TimeInLocalZone { get { return TimeZoneInfo.ConvertTime(utcDateTime, TimeZoneInfo.Local); } }
public DateTime TimeInSpecificZone(TimeZoneInfo tz)
{
return TimeZoneInfo.ConvertTime(utcDateTime, tz);
}
TimeZoneInfo.ConvertTime(dateTime, sourceTimeZone, destinationTimeZone)
进行转换。你需要为此创建一个自定义对象。你的自定义对象将包含两个值:
不确定是否已经有 CLR 提供的数据类型具有该功能,但至少 TimeZone 组件已经可用。
如果需要特定时区的带偏移量的日期/时间(既不是本地时间,也不是UTC时间),可以使用DateTimeOffset类:
var time = TimeSpan.Parse("9:00");
var est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
var nationalDateTime = new DateTimeOffset(DateTime.Today.Ticks + time.Ticks, est.BaseUtcOffset);
TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById(TimeZones.Paris.Id));
TimeZones.Paris.Id
的值? - InteXX我在Jon Skeet的答案基础上添加了一些额外的内容,使其更接近于DateTime
。大部分情况下,这将简化比较、相等性和转换。我发现DateTimeZoned.Now("")
函数特别有用。
需要注意的一点是,这个结构体是在.NET 6中编写的。因此,如果您使用的是旧版本,可能需要替换一些新语言特性的用法。
此外,运算符和接口的实现受到了GitHub上的DateTime.cs .NET参考的启发。
/// <summary>
/// This value type represents a date and time with a specific time zone applied. If no time zone is provided, the local system time zone will be used.
/// </summary>
public readonly struct DateTimeZoned : IComparable, IComparable<DateTimeZoned>, IEquatable<DateTimeZoned>
{
/// <summary>
/// Creates a new zoned <see cref="DateTime"/> with the system time zone.
/// </summary>
/// <param name="dateTime">The local <see cref="DateTime"/> to apply a time zone to.</param>
public DateTimeZoned(DateTime dateTime)
{
var local = DateTime.SpecifyKind(dateTime, DateTimeKind.Local);
UniversalTime = TimeZoneInfo.ConvertTimeToUtc(local, TimeZoneInfo.Local);
TimeZone = TimeZoneInfo.Local;
}
/// <summary>
/// Creates a new zoned <see cref="DateTime"/> with the specified time zone.
/// </summary>
/// <param name="dateTime">The <see cref="DateTime"/> to apply a time zone to.</param>
/// <param name="timeZone">The time zone to apply.</param>
/// <remarks>
/// Assumes the provided <see cref="DateTime"/> is from the specified time zone.
/// </remarks>
public DateTimeZoned(DateTime dateTime, TimeZoneInfo timeZone)
{
var unspecified = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);
UniversalTime = TimeZoneInfo.ConvertTimeToUtc(unspecified, timeZone);
TimeZone = timeZone;
}
/// <summary>
/// Creates a new zoned <see cref="DateTime"/> with the specified time zone.
/// </summary>
/// <param name="dateTime">The <see cref="DateTime"/> to apply a time zone to.</param>
/// <param name="timeZone">The time zone to apply.</param>
/// <remarks>
/// Assumes the provided <see cref="DateTime"/> is from the specified time zone.
/// </remarks>
public DateTimeZoned(DateTime dateTime, string timeZone)
{
var unspecified = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);
var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZone);
UniversalTime = TimeZoneInfo.ConvertTimeToUtc(unspecified, timeZoneInfo);
TimeZone = timeZoneInfo;
}
/// <summary>
/// The UTC <see cref="DateTime"/> for the stored value.
/// </summary>
public DateTime UniversalTime { get; init; }
/// <summary>
/// The selected time zone.
/// </summary>
public TimeZoneInfo TimeZone { get; init; }
/// <summary>
/// The localized <see cref="DateTime"/> for the stored value.
/// </summary>
public DateTime LocalTime => TimeZoneInfo.ConvertTime(UniversalTime, TimeZone);
/// <summary>
/// Specifies whether UTC and localized values are the same.
/// </summary>
public bool IsUtc => UniversalTime == LocalTime;
/// <summary>
/// Returns a new <see cref="DateTimeZoned"/> with the current <see cref="LocalTime"/> converted to the target time zone.
/// </summary>
/// <param name="timeZone">The time zone to convert to.</param>
public DateTimeZoned ConvertTo(string timeZone)
{
var converted = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(LocalTime, TimeZone.Id, timeZone);
return new DateTimeZoned(converted, timeZone);
}
/// <summary>
/// Returns a new <see cref="DateTimeZoned"/> with the current <see cref="LocalTime"/> converted to the target time zone.
/// </summary>
/// <param name="timeZone">The time zone to convert to.</param>
public DateTimeZoned ConvertTo(TimeZoneInfo timeZone)
{
var converted = TimeZoneInfo.ConvertTime(LocalTime, TimeZone, timeZone);
return new DateTimeZoned(converted, timeZone.Id);
}
/// <summary>
/// Returns the value as a string in the round-trip date/time pattern.
/// </summary>
/// <remarks>
/// This applies the .ToString("o") option on <see cref="LocalTime"/>.
/// </remarks>
public string ToLocalString()
{
var local = new DateTimeOffset(LocalTime, TimeZone.BaseUtcOffset);
return local.ToString("o");
}
/// <summary>
/// Returns the value as a string in the universal sortable date/time pattern.
/// </summary>
/// <remarks>
/// This is applies the .ToString("u") option on <see cref="UniversalTime"/>.
/// </remarks>
public string ToUniversalString()
{
return UniversalTime.ToString("u");
}
/// <summary>
/// Returns a <see cref="DateTime"/> representing the current date and time adjusted to the system time zone.
/// </summary>
/// <remarks>
/// This is functionally equivalent to <see cref="DateTime.Now"/> and has been added for completeness.
/// </remarks>
public static DateTime Now() => TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Local);
/// <summary>
/// Returns a <see cref="DateTime"/> representing the current date and time adjusted to the specified time zone.
/// </summary>
/// <param name="timeZone">The time zone to apply.</param>
public static DateTime Now(TimeZoneInfo timeZone) => TimeZoneInfo.ConvertTime(DateTime.UtcNow, timeZone);
/// <summary>
/// Returns a <see cref="DateTime"/> representing the current date and time adjusted to the specified time zone.
/// </summary>
/// <param name="timeZone">The time zone to apply.</param>
public static DateTime Now(string timeZone)
{
var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZone);
return TimeZoneInfo.ConvertTime(DateTime.UtcNow, timeZoneInfo);
}
/// <inheritdoc/>
public override bool Equals(object? value)
{
return value is DateTimeZoned d2 && this == d2;
}
/// <inheritdoc/>
public bool Equals(DateTimeZoned value)
{
return this == value;
}
/// <summary>
/// Compares two <see cref="DateTimeZoned"/> values for equality.
/// </summary>
/// <param name="d1">The first value to compare.</param>
/// <param name="d2">The second value to compare.</param>
/// <returns>
/// Returns <see langword="true"/> if the two <see cref="DateTimeZoned"/> values are equal, or <see langword="false"/> if they are not equal.
/// </returns>
public static bool Equals(DateTimeZoned d1, DateTimeZoned d2)
{
return d1 == d2;
}
/// <summary>
/// Compares two <see cref="DateTimeZoned"/> values, returning an integer that indicates their relationship.
/// </summary>
/// <param name="d1">The first value to compare.</param>
/// <param name="d2">The second value to compare.</param>
/// <returns>
/// Returns 1 if the first value is greater than the second, -1 if the second value is greater than the first, or 0 if the two values are equal.
/// </returns>
public static int Compare(DateTimeZoned d1, DateTimeZoned d2)
{
var ticks1 = d1.UniversalTime.Ticks;
var ticks2 = d2.UniversalTime.Ticks;
if (ticks1 > ticks2)
return 1;
else if (ticks1 < ticks2)
return -1;
else
return 0;
}
/// <inheritdoc/>
public int CompareTo(object? value)
{
if (value == null)
return 1;
if (value is not DateTimeZoned)
throw new ArgumentException(null, nameof(value));
return Compare(this, (DateTimeZoned)value);
}
/// <inheritdoc/>
public int CompareTo(DateTimeZoned value)
{
return Compare(this, value);
}
/// <inheritdoc/>
public override int GetHashCode()
{
var ticks = UniversalTime.Ticks;
return unchecked((int)ticks) ^ (int)(ticks >> 32);
}
public static TimeSpan operator -(DateTimeZoned d1, DateTimeZoned d2) => new(d1.UniversalTime.Ticks - d2.UniversalTime.Ticks);
public static bool operator ==(DateTimeZoned d1, DateTimeZoned d2) => d1.UniversalTime.Ticks == d2.UniversalTime.Ticks;
public static bool operator !=(DateTimeZoned d1, DateTimeZoned d2) => d1.UniversalTime.Ticks != d2.UniversalTime.Ticks;
public static bool operator <(DateTimeZoned d1, DateTimeZoned d2) => d1.UniversalTime.Ticks < d2.UniversalTime.Ticks;
public static bool operator <=(DateTimeZoned d1, DateTimeZoned d2) => d1.UniversalTime.Ticks <= d2.UniversalTime.Ticks;
public static bool operator >(DateTimeZoned d1, DateTimeZoned d2) => d1.UniversalTime.Ticks > d2.UniversalTime.Ticks;
public static bool operator >=(DateTimeZoned d1, DateTimeZoned d2) => d1.UniversalTime.Ticks >= d2.UniversalTime.Ticks;
}