在C#中,使用DateTime
類可以方便地進行日期計算。以下是一些常見的日期計算方法:
DateTime currentDate = DateTime.Now;
DateTime futureDate = currentDate.AddDays(5); // 添加5天
DateTime pastDate = currentDate.SubtractDays(5); // 減去5天
DateTime currentDate = DateTime.Now;
DateTime futureDate = currentDate.AddMonths(3); // 添加3個月
DateTime pastDate = currentDate.SubtractMonths(3); // 減去3個月
DateTime currentDate = DateTime.Now;
DateTime futureDate = currentDate.AddYears(2); // 添加2年
DateTime pastDate = currentDate.SubtractYears(2); // 減去2年
DateTime currentDate = DateTime.Now;
DateTime otherDate = new DateTime(2022, 1, 1);
TimeSpan difference = currentDate - otherDate; // 計算兩個日期之間的差值
int days = difference.Days; // 獲取差值中的天數部分
DateTime currentDate = DateTime.Now;
int year = currentDate.Year;
int month = currentDate.Month;
DateTime lastDayOfMonth = new DateTime(year, month + 1, 0); // 注意:month + 1,因為DateTime的Month屬性是從0開始的
DateTime date1 = new DateTime(2022, 6, 1);
DateTime date2 = new DateTime(2023, 6, 1);
bool isSameYear = date1.Year == date2.Year; // 輸出:False
DateTime currentDate = DateTime.Now;
int year = currentDate.Year;
int month = currentDate.Month;
DateTime firstDayOfMonth = new DateTime(year, month, 1);
這些方法可以根據需要進行組合和擴展,以滿足不同的日期計算需求。