簡體   English   中英

獲取所選月份的第一個和最后一個日期 c# winforms

[英]Getting first and last date of selected month c# winforms

在開始之前,我想告訴您我已經知道如何選擇當月的第一個和最后一個日期。 但是,我的問題是不同的,我想使用 c# winforms date-time picker選擇所選月份的第一個和最后一個日期。

public Form1()
{
    InitializeComponent();          

    MonthYearDT();
}

private string MonthYearDT()
{

        dTMY.Format = DateTimePickerFormat.Custom;
        dTMY.CustomFormat = "yyyy-MM-dd";
        dTMY.ShowUpDown = true; // to prevent the calendar from being displayed


        return dTMY.Value.ToString("yyyy-MM-dd"); 
}

private void BtnExecute_Click(object sender, EventArgs e)
{
    .
    .
    .
    .

      monthYear = MonthYearDT();
    .
    .
    .
}

上面的monthYear值為2019-12-19 它可以更改為任何月份。 我想獲得所選月份的第一個2019-12-01和最后一個日期2019-12-31

我怎樣才能做到這一點?

任何幫助將不勝感激。

在做任何事情之前,首先將函數MonthYearDT()string更改為DateTime

private DateTime MonthYearDT()
{
        dTMY.Format = DateTimePickerFormat.Custom;
        dTMY.CustomFormat = "yyyy-MM";
        dTMY.ShowUpDown = true; // to prevent the calendar from being displayed
        dTMY.Enabled = false;
        return dTMY.Value; 
}

獲得第一個很容易。 只需像這樣創建一個新的DateTime

DateTime selectedDate = MonthYearDT();

var first = new DateTime(selectedDate.Year, selectedDate.Month, 1);

獲得第二個同樣容易。 first ,像這樣加一個月減一天

var second = first.AddMonths(1).AddDays(-1);

firstDate = first.ToString("yyyy-MM-dd");
lastDate = second.ToString("yyyy-MM-dd");

普遍的事實是,任何一個月的第一天總是相同的。

並可以使用 DateTime 函數獲取最后一個日期。 您還需要在月份中使用年份才能獲得最后一天

var lastDay = DateTime.DaysInMonth(year, month);
var lastDayDate = new DateTime(year, month, lastDay);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM