修改 linq 查询以将字段从日期时间转换为字符串

modify linq query to turn field from datetime to string

所以我有一个 linq 表达式,它选择用户选择的特定日期时间之间的一组记录。但是,在将 callDate 用作日期时间类型后,我需要在输出之前将其转换为字符串

当前代码:

[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

型号:

[Required]
public DateTime callDate { get; set; }

如果您希望将 CallDate return编辑为字符串,则需要 select 您的结果作为新的对象类型。这可以是您创建的 class,也可以是匿名类型,或者只是日期。示例:

//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() }; 

如果您在同一个块中使用匿名类型,那很好,或者 return 从您的 API 中获取它,但也许不要 return 从方法中获取它在别处使用。很难处理匿名类型。 (http://codeblog.jonskeet.uk/2009/01/09/horrible-grotty-hack-returning-an-anonymous-type-instance/)

编辑: 好的,看来您正在 return 从您的 api 控制器获取细节模型。在这种情况下,您无法更改 CallDate 的类型(除非您如上所述创建一个新的 class),但您可以控制 Date 序列化的格式(默认为 ISO 8601 [2009-02-15T00:00:00Z]. 检查这个 Whosebug 问题以了解如何设置自定义格式化程序以特定格式输出日期:

Specifying a custom DateTime format when serializing with Json.Net