DateTime 使用小结
//今天
DateTime.Now.Date.ToString();
//昨天
DateTime.Now.AddDays(-1).ToString();
//明天
DateTime.Now.AddDays(1).ToString();
//本週第1天及最後1天 (要注意的是這裡的每一週是從週日始至週六止)
DateTime.Today.AddDays (-(int)DateTime.Today.DayOfWeek).ToString();
DateTime.Today.AddDays (6 -(int)DateTime.Today.DayOfWeek).ToString();
//上週, 一個周是7天,上週就是本週再減去7天
DateTime.Today.AddDays (-(int)DateTime.Today.DayOfWeek - 7).ToString();
DateTime.Today.AddDays (6 -(int)DateTime.Today.DayOfWeek - 7).ToString();
//下周
DateTime.Today.AddDays (-(int)DateTime.Today.DayOfWeek + 7).ToString();
DateTime.Today.AddDays (6 -(int)DateTime.Today.DayOfWeek + 7).ToString();
//巧用C#裡ToString的字符格式化
//本用第1天及最後1天
DateTime.Now.ToString("yyyy-MM-01");
DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01")).AddMonths(1).AddDays(-1).ToString();
//上個月第1天及最後1天
DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01")).AddMonths(-1).ToString();
DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01")).AddDays(-1).ToString();
//下個月第1天及最後1天
DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01")).AddMonths(1).ToString();
DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01")).AddMonths(2).AddDays(-1).ToString();
//今年第1天
DateTime.Parse(DateTime.Now.ToString("yyyy-01-01")).ToString();
//今年最後1天
DateTime.Parse(DateTime.Now.ToString("yyyy-01-01")).AddYears(1).AddDays(-1).ToString();