Arturo Martinez
Arturo Martinez

Reputation: 385

Linq Date Distinct as String yyyy-mm-dd

I have a date sql variable i retrive with a Linq statement however i need it to be in a format like 'yyyy-MM-dd' but i dotn know how to do this in c#

This is my Linq:

  List<string> listItem2 = new List<string>();

foreach (var item in db.Pos.Select(l => l.Fecha).Distinct())
        {
            string dateday = Convert.ToString(item);
            string lines = dateday.Split(' ')[0];
            listItem2.Add(item.ToString());
        }

How ever my output ends like this 'dd/mm/yyyy' how can i make it 'yyyy-MM-dd'??

Upvotes: 1

Views: 637

Answers (2)

sujith karivelil
sujith karivelil

Reputation: 29036

You can try this:

  string dateday = item.ToString("yyyy-MM-dd");

So your loop will be like the following:

 foreach (var item in db.Pos.Select(l => l.Fecha).Distinct())
    {
        string dateday = item.ToString("yyyy-MM-dd");
        string lines = dateday.Split('-')[0];
        listItem2.Add(item.ToString());
    }

Instead for Convert.ToString(item); for displaying date in the given format("yyyy-mm-dd").

Upvotes: 4

nobody
nobody

Reputation: 11090

List<string> listItem2 = new List<string>();

foreach (var item in db.Pos.Select(l => l.Fecha).Distinct())
   listItem2.Add(item.ToString("yyyy-MM-dd"));

Upvotes: 0

Related Questions