我有label1 label2和button1,其中我按下button1,label1文本将根据上个月的总天数(比如'31'天)更改,label2文本将根据去年的总天数(假设为'365'天)进行更改
我只知道如何编码上个月使用DateTime.DaysInMonth的总天数,但没有DateTime.DaysInYear的方法不是它
这是我的代码
private void button1_Click(object sender, EventArgs e)
{
//Last Month
string month = DateTime.Now.ToString("MM");
int months = Int32.Parse(month);
int previousmonths = months - 1;
//Month in this Year
string year = DateTime.Now.ToString("yyyy");
int years = Int32.Parse(year);
int daysmonth = DateTime.DaysInMonth(years, previousmonths);
MessageBox.Show(daysmonth.ToString());
//Last Year
string year = DateTime.Now.ToString("yyyy");
int years = Int32.Parse(year);
int lastyears = years - 1;
int daysyear = DateTime.DaysInYear(lastyears);
MessageBox.Show(daysyear.ToString());
}
Run Code Online (Sandbox Code Playgroud)
据我记忆,一年(闰年)总有365天(366天).
你可以简单地使用DateTime.IsLeapYear:
public static int DaysInYear(int year)
{
return DateTime.IsLeapYear(year) ? 366 : 365;
}
Run Code Online (Sandbox Code Playgroud)
但是,看看你的代码,我认为你过于复杂.
您不需要将DateTime格式化为字符串,然后再次解析它.
您的代码可以更清晰的方式重写:
// Days in previous Month
var monthAgo = DateTime.Now.AddMonths(-1);
int daysMonth = DateTime.DaysInMonth(monthAgo.Year, monthAgo.Month);
MessageBox.Show(daysMonth.ToString());
// Days in Previous Year
int daysYear = DaysInYear(DateTime.Now.Year - 1); // see my function above
MessageBox.Show(daysYear.ToString());
Run Code Online (Sandbox Code Playgroud)
上个月和去年有一些更优雅的方式.
var lastMonth = DateTime.Now.AddMonths(-1).Month;
var lastYear = DateTime.Now.AddYears(-1).Year;
Run Code Online (Sandbox Code Playgroud)
从那里开始,获得一年中的天数很简单,就像耶尔达指出的那样:
var daysInLastYear = DateTime.IsLeapYear(yelastYear) ? 366 : 365;
Run Code Online (Sandbox Code Playgroud)