Reputation: 1329
So I have a linq expression that that selects a group of records between a certain datetime, as chosen by the user. However, after the callDate is used as a datetime type I need it turned into a string before it is output
Current Code:
[ResponseType(typeof(Detail))]
public IHttpActionResult GetDetail(string StartDate, string EndDate)
{
DateTime StartDateTime = DateTime.ParseExact(StartDate, "yyyyMMddhhmm", null);
DateTime EndDateTime = DateTime.ParseExact(EndDate, "yyyyMMddhhmm", null);
var detail = from a in db.Details where (a.callDate >= StartDate && a.callDate <= EndDate) select a
Model:
[Required]
public DateTime callDate { get; set; }
Upvotes: 0
Views: 78
Reputation: 9508
If you want CallDate to be returned as a string, you need to select your results as a new object type. This can either be a class you have created, or an anonymous type, or just the date. Examples:
//class
IEnumerable<MyConvertedClass> details = db.Details.Where(a => a.callDate >= StartDate && a.callDate <= EndDate)
.ToList().Select(a => new MyConvertedClass { Id = a.Id, CallDate = a.CallDate.ToShortDateString() });
//where MyConvertedClass looks like this:
public class MyConvertedClass {
public int Id { get; set; }
public string CallDate { get; set; }
}
//just the dates
IEnumerable<DateTime> details = from a in db.Details where (a.callDate >= StartDate && a.callDate <= EndDate)
select a.CallDate;
//anonymous type
var detail = from a in db.Details where (a.callDate >= StartDate && a.callDate <= EndDate)
select new { Id = a.Id, CallDate = a.CallDate.ToShortDateString() };
If you are using the anonymous type in the same block it's fine, or returning it from your API, but maybe don't return it from a method to be used elsewhere. It's hard to deal with anonymous types. (http://codeblog.jonskeet.uk/2009/01/09/horrible-grotty-hack-returning-an-anonymous-type-instance/)
EDIT:
Okay, so it looks like you are returning the Detail model from your api controller. In this case, you can't change the type of CallDate (unless you create a new class as above), but you can control the format that the Date is serialized in (default is ISO 8601 [2009-02-15T00:00:00Z
]. Check this stackoverflow question to see how to set up a custom formatter to output the date in a particular format:
Specifying a custom DateTime format when serializing with Json.Net
Upvotes: 1