使用正则表达式提取括号内的时间戳数值,将其解析为自1970年1月1日以来的毫秒数,并加上1970年的时间起点即可得到正确的日期对象。具体做法是调用 regex.match 获取匹配项,通过 convert.toint64 转换字符串,最后用 datetimeoffset.fromunixtimemilliseconds 或手动计算偏移量生成 datetime 实例。

如何从/Date(1234567890)/中提取有效数字
直接对输入字符串应用正则表达式 /Date\(([^)]+)\)/ 可以精准捕获中间的数字部分。该模式以字面量 /Date( 开头,利用非贪婪或非捕获组提取括号内的内容,并以 ) 结尾。如果字符串格式不匹配,则返回空结果,避免后续解析出错。

using System;
using System.Text.RegularExpressions;
public class DateParser
{
public static string ExtractTimestamp(string input)
{
Match match = Regex.Match(input, @"\/Date\(([^)]+)\)\/?");
if (match.Success)
{
return match.Groups[1].Value;
}
return null;
}
}
上述代码定义了 ExtractTimestamp 方法,接收如 /Date(1234567890)/ 的字符串。若输入合法,返回纯数字字符串 1234567890;否则返回 null。这是转换流程的第一步,确保只处理有效数据。
如何将提取的时间戳转换为DateTime对象
将上一步得到的毫秒级时间戳字符串转换为 long 类型后,基于 Unix 纪元(1970-01-01T00:00:00Z)创建 DateTime 对象。由于 C# 的 DateTime 默认表示本地时间或 UTC,需明确指定 Kind 以避免时区混淆。推荐使用 DateTimeOffset 进行安全转换,再转为 DateTime。

using System;
public class DateConverter
{
public static DateTime ConvertToDateTime(string timestampStr)
{
long milliseconds = Convert.ToInt64(timestampStr);
DateTimeOffset dto = DateTimeOffset.FromUnixTimeMilliseconds(milliseconds);
return dto.UtcDateTime;
}
}
此段代码展示了完整的转换逻辑。输入为 1234567890,输出为对应的 UTC 时间。若需本地时间,可调用 dto.LocalDateTime。该方法处理了常见的 JSON 序列化遗留格式,适用于旧系统数据迁移场景。
当时间戳包含时区信息或格式异常时会发生什么
标准 /Date(...)/ 格式通常不包含时区后缀,仅表示 UTC 毫秒数。若旧系统返回类似 /Date(1234567890000+0800)/ 的变体,正则表达式需调整以兼容可选的时区偏移。此外,若时间戳为秒级而非毫秒级,直接按毫秒解析会导致日期偏差至公元5138年左右。因此,需根据实际数据源确认单位,并在代码中加入校验逻辑。











