将时间跨度转换为日期时间

时间:2015-09-18 05:21:44

标签: c# datetime

我的功能是:

public async Task<IHttpActionResult> RecentAddedTags(int daysago)
{
    TimeSpan duration = DateTime.UtcNow - DateTime.Today.AddDays(-daysago);
    DateTime days = DateTime.UtcNow - duration;
    var ret = from tag in db.Tags
    where tag.time.Equals(days)
    select new
    {
        postedById = tag.AspNetUser.Id,
        postedByName = tag.AspNetUser.UserName,
        name = tag.name,
        info = tag.info,
        time = tag.time,
        id = tag.Id,
    };
    return Ok(ret);
}

如果我将该函数称为RecentAddedTags(2),它应该返回2天前创建的所有标记。但它给出了错误:

  

无法创建类型&#39; System.Object&#39;的常量值。只要   在此上下文中支持原始类型或枚举类型。

days对象存在一些问题。我做错了什么?

2 个答案:

答案 0 :(得分:2)

在DateTime对象中比较日期,它将适合你

    var ret = from tag in db.Tags.ToList()
              where tag.time.Date == days.Date
              select new
              {
                    postedById = tag.AspNetUser.Id,
                    postedByName = tag.AspNetUser.UserName,
                    name = tag.name,
                    info = tag.info,
                    time = tag.time,
                    id = tag.Id,
              };

答案 1 :(得分:1)

您需要更改

tag.time.Equals(days)

tag.time == days;

(不完全确定它为何起作用)