1
votes

I am using web api 2 with entity framework v 6.0.0 . I have a table that contains a date column called StudyGroupStartDate so i used the data annotations like this:

    [Column(TypeName = "Date")]
    public DateTime? StudyGroupStartDate { get; set; }

And this is how it is saved in the database : 7/20/2015. However when i retrieve it and display it is returned like this : 2015-07-20T00:00:00 (I want it to be like how it's saved in the database)

Note that i am not using MVC , i created an empty web application and chose web api so i am just using controllers that were generated using the model.And this is an example of my controller.

    // GET: api/StudyGroups
    public List<StudyGroup> GetStudyGroups()
    {
        return db.StudyGroups.Where(a=>a.IsDeleted==false).ToList();
    }

I just changed the generated code of the GET request to retrieve the result as a list with a condition of is_deleted to be false.

1

1 Answers

0
votes

I don't know what really is your issue. You have to format the DateTime in your front-end, i.e., parse this date time value (2015-07-20T00:00:00) and then format as you want.

Other possibility is cast the DateTime as String, doing something like this:

// GET: api/StudyGroups
public List<Object> GetStudyGroups()
{
    return db.StudyGroups.Where(a=>a.IsDeleted==false)
      .Select(it => new { studyGroup = it, it.StudyGroupStartDate.ToString("M/dd/yyyy") })
      .ToList();
}

There's a third possibility, but that is too tricky I think: you can create a String property to return only this field as String, with the format you want (see below):

[Column(TypeName = "Date")]
public DateTime? StudyGroupStartDate { get; set; }

[Column(TypeName = "DateStr")]
public String StudyGroupStartDateStr { 
  get {
    return StudyGroupStartDate.ToString("M/dd/yyyy");
  }
}

Remember: in this case, you need to use/show the DateStr column, instead of the Date column.