-3

How to format date in 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?

Here is my code:

This is part of linq query.I am tring to format and concatinate two columns.

select new abc
                           {
                               cardDates = (cad.Key.SchStartDT.ToString("dd/MM/yyyy") + "-" + cad.Key.SchEndDT.ToString("dd/MM/yyyy"))
                           });
user3161958
  • 25
  • 2
  • 11

1 Answers1

0

This code works for (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();
}

For Linq to Entities case, check this answer Formatting date in Linq-to-Entities query causes exception

Community
  • 1
  • 1
Omar.Alani
  • 4,050
  • 2
  • 20
  • 31