Câu trả lời:
Bạn muốn DateTime.DaysInMonth
:
int days = DateTime.DaysInMonth(year, month);
Rõ ràng là nó thay đổi theo năm, vì đôi khi tháng hai có 28 ngày và đôi khi 29. Bạn luôn có thể chọn một năm cụ thể (nhảy hoặc không) nếu bạn muốn "sửa" nó thành giá trị này hay giá trị khác.
Sử dụng System.DateTime.DaysInMonth , từ mẫu mã:
const int July = 7;
const int Feb = 2;
// daysInJuly gets 31.
int daysInJuly = System.DateTime.DaysInMonth(2001, July);
// daysInFeb gets 28 because the year 1998 was not a leap year.
int daysInFeb = System.DateTime.DaysInMonth(1998, Feb);
// daysInFebLeap gets 29 because the year 1996 was a leap year.
int daysInFebLeap = System.DateTime.DaysInMonth(1996, Feb);
Để tìm số ngày trong một tháng, lớp DateTime cung cấp phương thức "DaysInMonth (int year, int tháng)". Phương pháp này trả về tổng số ngày trong một tháng được chỉ định.
public int TotalNumberOfDaysInMonth(int year, int month)
{
return DateTime.DaysInMonth(year, month);
}
HOẶC LÀ
int days = DateTime.DaysInMonth(2018,05);
Đầu ra: - 31
int days = DateTime.DaysInMonth(int year,int month);
hoặc là
int days=System.Globalization.CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(int year,int month);
bạn phải vượt qua năm và tháng vì int
sau đó các ngày trong tháng sẽ được hoàn trả vào năm và tháng
Tôi đã làm cho nó tính toán ngày trong tháng từ datetimepicker được chọn tháng và năm, và tôi nhưng mã trong datetimepicker1 được chuyển đổi để trả về kết quả trong hộp văn bản có mã này
private void DateTimePicker1_ValueChanged(object sender, EventArgs e)
{
int s = System.DateTime.DaysInMonth(DateTimePicker1.Value.Date.Year, DateTimePicker1.Value.Date.Month);
TextBox1.Text = s.ToString();
}
int month = Convert.ToInt32(ddlMonth.SelectedValue);/*Store month Value From page*/
int year = Convert.ToInt32(txtYear.Value);/*Store Year Value From page*/
int days = System.DateTime.DaysInMonth(year, month); /*this will store no. of days for month, year that we store*/