當前文章的短網址連結為: https://unos.top/uf4r
假设有实体类Person
public class Person : object
{
public string? Name;
public DateTimeOffset Born;
public override string ToString()
{
return $"{Name} was born on {Born:d}.";
}
}
Swift测试实例化对象
Person p = new()
{
Name = "Jerry",
Born = new DateTimeOffset(
year: 1965, month: 12, day: 22,
hour: 16, minute: 28, second: 0,
offset: TimeSpan.FromHours(-5)) // US Eastern Standard Time.
};
WriteLine(p);
SwiftJerry was born on 22/12/1965.
Swift**关于new DateTimeOffset() 初始化参数offset
的含义**:
该参数表示该时间点相对于协调世界时(UTC)的时差
TimeSpan.FromHours(-5)
表示该时间属于 UTC-5 时区(如北美东部标准时间 EST)。- 示例中的时间
1965-12-22 16:28:00
实际等同于:UTC 时间 1965-12-22 21:28:00
(因为16:28 + 5小时 = 21:28 UTC
)。
若要表达中国时间,中国采用 UTC+8 时区(无夏令时),设置方式如下:
bob.Born = new DateTimeOffset(
year: 1965, month: 12, day: 22,
hour: 16, minute: 28, second: 0,
offset: TimeSpan.FromHours(8) // UTC+8(北京时间)
);
Swift替代方案(推荐):
使用 .ToOffset()
方法转换时区更安全
// 先定义 UTC 时间或本地时间
var utcTime = new DateTime(1965, 12, 22, 8, 28, 0, DateTimeKind.Utc);
p.Born = new DateTimeOffset(utcTime).ToOffset(TimeSpan.FromHours(8));
Swift注意⚠️
对夏令时区域,建议用 TimeZoneInfo
转换(如 TimeZoneInfo.ConvertTimeBySystemTimeZoneId
)。