WPFKK
WPFKK

Reputation: 1477

Getting a days collection from System.DateTime for a given month in custom format in WPF/C#

I am looking to get a list of days in the following format: Jan 1, Jan 3.....Jan 30, Jan 31.

I can generate this collection by my self by calling DateTime.DaysInMonth(2013,01); But this just gives me "31" so i will have to loop through them and generate collection. But will there be any custom methods already that does this easily or in simple way.

Thanks

Upvotes: 0

Views: 334

Answers (4)

Tim Schmelter
Tim Schmelter

Reputation: 460078

You can use Linq:

DateTime date = new DateTime(2013, 1, 1);
var cal = System.Globalization.CultureInfo.CurrentCulture.Calendar;
List<String> monthDates = Enumerable.Range(0, cal.GetDaysInMonth(date.Year, date.Month))
    .Select(i => date.AddDays(i).ToString("MMM d"))
    .ToList();

Demo

Upvotes: 2

Ilya Ivanov
Ilya Ivanov

Reputation: 23626

Try to use next code snippet. Consider using the MMM DateTime pattern to extract month name

Enumerable.Range(1, DateTime.DaysInMonth(2012, 1))
          .Select(num => num +" Jan");

returns

1 Jan 
2 Jan 
3 Jan 
...
30 Jan 
31 Jan 

Edit: To extract month name you can use next code snippet

var start = new DateTime(2012, 1, 1);
Enumerable.Range(0, DateTime.DaysInMonth(2012, 1))
          .Select(days => start.AddDays(days))
          .Select(day => day.ToString("d MMM")); // returns the same

Upvotes: 4

RobbieK
RobbieK

Reputation: 115

Based on Ilya Ivanov's answer above, if you wanted the list to show the format "Jan ??", you could do the following:

var list = Enumerable.Range(1, DateTime.DaysInMonth(2012, 1)).Select(num => "Jan " + num);

Upvotes: 0

CodingGorilla
CodingGorilla

Reputation: 19842

I don't think there are any built in methods to do this, but you could easily do something like:

DateTime.DaysInMonth(2013, 01).Select(x=> "Jan " + x.Tostring()).ToList();

You can see how you can easily parameterize and make your own function out of this to get you the different months as well.

Upvotes: 0

Related Questions