我有一个返回日期时间字段的 Web 服务。
我得到一个结果 /Date(1379048144000)/
但是
我只想要 1379048144000
我该如何实现。
[WebMethod]
public DateTime GetServerDate()
{
return DateTime.Now;
}
通过设置Header Content-Type: application/json;字符集=utf-8;我得到了类似 /Date(1379048144000)/
的结果。
最佳答案
您可以更改 WS 以返回带有 DateTime 值的 long。返回值是自 Unix 纪元 (01/01/1970) 以来的毫秒数。这可以通过 DateTime
上的扩展方法来完成,例如:
public static class DateTimeExtensions
{
...
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1);
public static long ToUnixTime(this DateTime dateTime)
{
return (dateTime - UnixEpoch).Ticks / TimeSpan.TicksPerMillisecond;
}
...
}
您的网络服务方法可能类似于:
public long GetMyDate(...)
{
DateTime dateTime = ...;
return dateTime.ToUnixTime();
}
关于c# - 将日期时间转换为 JSON 日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18820896/