简体   繁体   中英

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

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

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

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.

根据上述Ilya Ivanov的答案,如果您希望列表显示格式为“ Jan ??”,则可以执行以下操作:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM