How to get first and last day in month view at DateTimePicker

1.8k views Asked by At

I have a DataTimePicker in a Forms application. Is there an easy way (preferably in C#) to get the first and last shown day of a month. So for example for 1st of December I like to get the 24th of November 2014 and the 4th of January 2015 as shown in the picture.

DateTimePicker Control

2

There are 2 answers

2
Fratyx On BEST ANSWER

I think it should be something like that (e.g. int year=2014; int month=12 for current month):

DateTime dt = new DateTime(year, month, 1);
int offset = ((int)dt.DayOfWeek - (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek + 6) % 7 + 1;
DateTime firstDate = dt.AddDays(-offset);
DateTime lastDate = firstDate.AddDays(41);

You can see that DateTimePicker puts the first of month in the first line except it is the first day of week. Then the first of month is in the second line. Therefore you have to look at the cultural settings for first day of week.

0
DevEstacion On

Here's another one I tried, It's working but i see that Fratyx already made an answer. So I'll just post it here.

private static void Main(string[] args)
{
    DateTime date = new DateTime(2014, 12, 1);
    var firstAndLastDays = getFirstDateInDatePicker(date);
}

private static Tuple<int, int> getFirstDateInDatePicker(DateTime date)
{
    int totalDaysInMonth = DateTime.DaysInMonth(date.Year, date.Month);
    int totalDiff = TOTAL_DAYS - totalDaysInMonth;
    DateTime firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
    DateTime lastDayOfMonth = new DateTime(date.Year, date.Month, totalDaysInMonth);
    int subtractor = (6 + (int)firstDayOfMonth.DayOfWeek) * -1;
    return new Tuple<int, int>(firstDayOfMonth.AddDays(subtractor).Day,
        lastDayOfMonth.AddDays(totalDiff + subtractor).Day);
}