You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何获取DateTime时区偏移并还原/Date()格式JSON日期

解决方法:保留并获取日期的时区偏移,还原/Date()格式

首先,你遇到的核心问题是DateTime类型本身不保留原始时区偏移信息——当你用DateTime反序列化/Date(...)格式的字符串时,Newtonsoft.Json会将其转换为UTC或本地时间(取决于配置),丢失了原始的-0500偏移。而DateTimeOffset类型专门用于存储包含时区偏移的日期时间,这才是你需要的类型。


1. 用DateTimeOffset反序列化,直接获取时区偏移

修改你的模型,将endDate属性的类型改为DateTimeOffset,这样反序列化时会完整保留原始的时间戳和时区偏移:

public class MyModel
{
    public DateTimeOffset endDate { get; set; }
}

// 反序列化
string jsonResponse = @"{'endDate': '/Date(-62135578800000-0500)/'}";
var model = JsonConvert.DeserializeObject<MyModel>(jsonResponse);

现在,你可以通过model.endDate.Offset获取到对应的时区偏移TimeSpan,然后将其格式化为-0500这样的字符串:

// 格式化偏移为±HHMM格式
string offsetString = model.endDate.Offset.ToString(@"hhmm");
// 结果会是 "-0500",和原始格式一致

如果要模拟JavaScript的getTimezoneOffset()方法(该方法返回UTC与本地时间的分钟差,比如UTC-5时区返回300),可以这样计算:

// JS getTimezoneOffset() = UTC时间 - 本地时间(分钟)
double jsStyleOffset = -model.endDate.Offset.TotalMinutes;
// 对于-05:00的偏移,结果是300,和JS返回值一致

2. 序列化回原始的/Date()格式

如果你希望再次序列化时回到/Date(...)格式,只需配置JsonSerializerSettings的DateFormatHandling为MicrosoftDateFormat:

var settings = new JsonSerializerSettings
{
    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
};

string serializedJson = JsonConvert.SerializeObject(model, settings);
// 输出结果:{"endDate":"/Date(-62135578800000-0500)/"}

如果你已经拿到时间戳,手动构造DateTimeOffset

如果你已经单独提取了时间戳-62135578800000,可以手动结合偏移构造DateTimeOffset:

// 时间戳转UTC DateTime
DateTime utcDateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
    .AddMilliseconds(-62135578800000);
// 构造带偏移的DateTimeOffset
DateTimeOffset dateTimeOffset = new DateTimeOffset(utcDateTime.AddHours(-5), TimeSpan.FromHours(-5));
// 同样可以通过Offset属性获取偏移

内容的提问来源于stack exchange,提问作者IBQ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:59:19