如何在Linq格式化日期--------------------------
Hi,
I am working on a linq query. I want to format date column to 'Mm/dd/yy' format. But, the Linq query shows error that Linq doesn't support formatting. Any help?
这是我的代码:
这是linq查询的一部分。我正在尝试格式化并连接两列。
select new abc
{
cardDates = (cad.Key.SchStartDT.ToString("dd/MM/yyyy") + "-" + cad.Key.SchEndDT.ToString("dd/MM/yyyy"))
});
答案 0 :(得分:0)
此代码适用于(LINQ to Objects case)
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
}
private static void Main(string[] args)
{
var people = new List<Person>
{
new Person
{
Id = 1,
Name = "James",
DateOfBirth = DateTime.Today.AddYears(-25),
},
new Person
{
Id = 2,
Name = "John",
DateOfBirth = DateTime.Today.AddYears(-20),
},
new Person
{
Id = 3,
Name = "Peter",
DateOfBirth = DateTime.Today.AddYears(-15),
}
};
var result = people.Select(t => new
{
t.Name,
DateStr = t.DateOfBirth.ToString("dd/MM/yyyy")
}).Take(2).ToList();
foreach (var r in result)
{
Console.WriteLine(r.Name);
Console.WriteLine(r.DateStr);
}
Console.ReadLine();
}
对于Linq to Entities案例,请检查此答案 Formatting date in Linq-to-Entities query causes exception