简体   繁体   中英

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

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控件

I think it should be something like that (eg 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.

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);
}

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