将DateTime转换为JSON DateTime [英] Convert DateTime To JSON DateTime
问题描述
我有一个返回日期时间字段的Web服务.
I have a WebService which return DateTime Field.
我得到一个结果/Date(1379048144000)/
但
我只想1379048144000
我怎么能做到这一点.
i want just 1379048144000
how can i achieve that.
[WebMethod]
public DateTime GetServerDate()
{
return DateTime.Now;
}
通过设置Header Content-Type:application/json; charset = utf-8;我得到了类似/Date(1379048144000)/
的结果.
by setting Header Content-Type: application/json; charset=utf-8; i got a result like /Date(1379048144000)/
.
推荐答案
您可以更改WS以返回带有DateTime值的long.返回的值是自Unix纪元(01/01/1970)以来的毫秒数.这可以通过DateTime
上的扩展方法来完成,例如:
You could change your WS to return a long with the value of the DateTime. The value to return is the number of milliseconds since the Unix Epoch (01/01/1970). This could be done with an extension method on DateTime
something like:
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;
}
...
}
您的Web服务方法可能类似于:
And your web service method might look something like:
public long GetMyDate(...)
{
DateTime dateTime = ...;
return dateTime.ToUnixTime();
}
这篇关于将DateTime转换为JSON DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!