获取所选月份的第一个和最后一个日期 c# winforms
Getting first and last date of selected month c# winforms
在开始之前,我想告诉您我已经知道如何 select 本月的第一个和最后一个日期。但是,我的问题是不同的,我想 select selected 月的第一个和最后一个日期使用 date-time picker
在 c# winforms
。
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
。它可以更改为任何月份。我想获取 select 月的第一个 2019-12-01
和最后一个日期 2019-12-31
。
我该怎么做?
如有任何帮助,我们将不胜感激。
普遍的真理是任何一个月的第一天总是相同的。
并且可以使用 DateTime 函数获取最后一个日期。您还需要年份才能得到最后一天
var lastDay = DateTime.DaysInMonth(year, month);
var lastDayDate = new DateTime(year, month, lastDay);
在做任何事情之前,首先将函数 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");
在开始之前,我想告诉您我已经知道如何 select 本月的第一个和最后一个日期。但是,我的问题是不同的,我想 select selected 月的第一个和最后一个日期使用 date-time picker
在 c# winforms
。
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
。它可以更改为任何月份。我想获取 select 月的第一个 2019-12-01
和最后一个日期 2019-12-31
。
我该怎么做?
如有任何帮助,我们将不胜感激。
普遍的真理是任何一个月的第一天总是相同的。
并且可以使用 DateTime 函数获取最后一个日期。您还需要年份才能得到最后一天
var lastDay = DateTime.DaysInMonth(year, month);
var lastDayDate = new DateTime(year, month, lastDay);
在做任何事情之前,首先将函数 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");