简体   繁体   English

如何使用Web API将C#DateTime序列化为Javascript日期

[英]How to serialize a C# DateTime as a Javascript Date using Web API

In MVC, you can do something like this: 在MVC中,您可以执行以下操作:

public ActionResult Index()
{
    return Json(new List<DateTime> { DateTime.Parse("19/02/2017") }, 
                JsonRequestBehavior.AllowGet);
}

And the returned value is ["\\/Date(1487458800000)\\/"] , which is a Javascript Date object. 返回的值为["\\/Date(1487458800000)\\/"] ,它是一个Javascript Date对象。

However, using WebAPI like this: 但是,像这样使用WebAPI:

public IEnumerable<DateTime> Get()
{
    return new List<DateTime> { DateTime.Parse("19/02/2017") };
}

The returned value is <dateTime>2017-02-19T00:00:00</dateTime> 返回值是<dateTime>2017-02-19T00:00:00</dateTime>

Is there any way that I can serialize a DateTime as a Javascript Date object using WebApi? 有什么方法可以使用WebApi将DateTime序列化为Javascript Date对象?

If you change your Accept header on your request to application/json you get: 如果将请求的Accept标头更改为application/json则会得到:

["2017-06-09T08:14:13.7729697-03:00"]

Try with a tool like Postman . 尝试使用Postman之类的工具。

In angular, you can do something like: 在Angular中,您可以执行以下操作:

var config = { headers:  {
        'Accept': 'application/json',
    }
};

$http.get("/api/values", config);

不过,您可以在JavaScript中使用该格式:

var myDate = new Date("2017-02-19T00:00:00");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM