在c#中将 datetimeoffset 序列化为json时,保留时区偏移的最直接方法是使用 system.text.json 并配置 jsonserializeroptions 的 writeindented 属性(如果需要格式化)以及确保序列化器默认行为正确。默认情况下,system.text.json 会将 datetimeoffset 序列化为 iso 8601 格式字符串,其中包含时区偏移信息(例如 +08:00)。如果使用的是较旧的 newtonsoft.json,则需要设置 dateformathandling 或使用自定义转换器。这里以现代 .net 默认的 system.text.json 为例,展示如何确保偏移量被保留。

System.Text.Json 默认行为是否保留偏移?
是的,System.Text.Json 默认会保留时区偏移。当序列化一个具有非零偏移量的 DateTimeOffset 对象时,输出字符串将包含该偏移量。例如,2023-10-27T10:00:00+08:00 中的 +08:00 就是偏移量。只要不手动截断或转换时区,原始偏移信息就会完整保留在 JSON 字符串中。

using System;
using System.Text.Json;
public class Program
{
public static void Main()
{
// 创建一个带有时区偏移的 DateTimeOffset 对象
// 假设当前时间是 UTC,但我们要模拟一个 +08:00 的偏移
var dto = new DateTimeOffset(2023, 10, 27, 10, 0, 0, TimeSpan.FromHours(8));
// 序列化选项
var options = new JsonSerializerOptions { WriteIndented = true };
// 序列化
string json = JsonSerializer.Serialize(dto, options);
Console.WriteLine(json);
}
}
运行上述代码,预期输出为:
"2023-10-27T10:00:00+08:00"
可以看到,+08:00 的偏移量被完整保留在 JSON 字符串中。这是 System.Text.Json 的标准行为,无需额外配置即可实现。
Newtonsoft.Json 如何处理时区偏移?
如果使用 Newtonsoft.Json,默认行为也是保留时区偏移,但可以通过 JsonSerializerSettings 进行更精细的控制。例如,可以设置 DateFormatString 来指定日期格式,或者使用 DateTimeZoneHandling 来处理时区转换。默认情况下,Newtonsoft.Json 也会输出包含偏移量的 ISO 8601 格式字符串。

通过 Playwright + HTTP 实现网页搜索与内容抓取,无需 API 密钥,支持国内 Bing CN 与国际 DuckDuckGo,自动获取排名前列的页面内容。
using System;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var dto = new DateTimeOffset(2023, 10, 27, 10, 0, 0, TimeSpan.FromHours(8));
// 序列化选项
var settings = new JsonSerializerSettings { DateFormatString = "yyyy-MM-ddTHH:mm:ssK" };
// 序列化
string json = JsonConvert.SerializeObject(dto, settings);
Console.WriteLine(json);
}
}
运行上述代码,预期输出为:
"2023-10-27T10:00:00+08:00"
通过设置 DateFormatString 为 "yyyy-MM-ddTHH:mm:ssK",我们确保了输出格式中包含时区偏移(K 代表时区)。这与 System.Text.Json 的默认行为一致,都保留了时区偏移信息。
反序列化时如何验证偏移量是否正确还原?
在反序列化 JSON 字符串时,System.Text.Json 和 Newtonsoft.Json 都会尝试将字符串解析回 DateTimeOffset 对象。为了验证偏移量是否正确还原,我们可以将序列化后的 JSON 字符串再次反序列化,并比较原始对象与反序列化后的对象是否相等。如果偏移量在序列化过程中丢失或错误,反序列化后的对象将与原始对象不一致。
using System;
using System.Text.Json;
public class Program
{
public static void Main()
{
var originalDto = new DateTimeOffset(2023, 10, 27, 10, 0, 0, TimeSpan.FromHours(8));
var options = new JsonSerializerOptions { WriteIndented = true };
string json = JsonSerializer.Serialize(originalDto, options);
// 反序列化
var deserializedDto = JsonSerializer.Deserialize<datetimeoffset>(json);
// 比较
bool isEqual = originalDto == deserializedDto;
Console.WriteLine($"Original: {originalDto}");
Console.WriteLine($"Deserialized: {deserializedDto}");
Console.WriteLine($"Equal: {isEqual}");
}
}
</datetimeoffset>
运行上述代码,预期输出为:
Original: 10/27/2023 10:00:00 +08:00 Deserialized: 10/27/2023 10:00:00 +08:00 Equal: True
这表明,在序列化后再反序列化,DateTimeOffset 对象的时区偏移量被正确还原,原始对象与反序列化后的对象完全相等。这验证了 System.Text.Json 在处理时区偏移时的可靠性。










