如何将DateTime值序列化为`yyyy-MM`? [重复]

问题描述 投票:-1回答:2

在ASP.NET MVC应用程序中,我以这种方式从数据库获取日期:

public class MonthController : ApiController

{
    public List<Month> monthContainer;

    public List<Month> getMonth()
    {
        DataContext dataContext = new DataContext();

        monthContainer = (from d in dataContext.Duties
                          select new Month()
                          {
                              MonthDate = d.Date
                          }).ToList();
        return monthContainer;
    }

答案中使用以下格式的日期:

{
    "MonthDate": "2015-10-01T00:00:00"
},
{
    "MonthDate": "2015-10-02T00:00:00"
}

因此,它将在MonthDate的每个月中的每一天进行到特定年份。如何才能以这种格式仅提取几个月而不加倍?如何更改控制器?我想要这种格式:

    "MonthDate": "2015-10"
    "MonthDate": "2015-11"
    "MonthDate": "2015-12"
    "MonthDate": "2016-01"
... "MonthDate": "2019-12"
c# asp.net-web-api json.net
2个回答
-1
投票

请使用DateTime.ParseExact,例如:


-1
投票

您必须使用parseExact方法,例如:

© www.soinside.com 2019 - 2024. All rights reserved.