How to serialize C # DateTime as Javascript date using web API

In MVC, you can do something like this:

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

      

And a value is returned ["\/Date(1487458800000)\/"]

which is a Javascript Date object.

However, using WebAPI do the following:

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

      

Return value <dateTime>2017-02-19T00:00:00</dateTime>

Is there any way to serialize DateTime as Javascript Date object using WebApi?

+3


source to share


2 answers


If you change the title Accept

as per your request to application/json

, you get:

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

      

Try it with a tool like Postman .



In angular, you can do something like:

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

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

      

0


source


You can use this format with JavaScript:



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

      

-1


source







All Articles