1、获取当前时间
DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.fff");
DateTime.Now.ToString();
DateTime.Now.ToLocalTime().ToString();
DateTime.Now.ToLongDateString().ToString();
DateTime.Now.ToShortDateString().ToString();
DateTime.Now.ToString("yyyy-MM-dd");
DateTime.Now.Date.ToString();
DateTime.Now.ToLongTimeString().ToString();
DateTime.Now.ToShortTimeString().ToString();
DateTime.Now.ToString("hh:mm:ss");
DateTime.Now.TimeOfDay.ToString();
DateTime.ToFileTime().ToString();
DateTime.Now.ToFileTimeUtc().ToString();
DateTime.Now.ToOADate().ToString();
DateTime.Now.ToUniversalTime().ToString();
DateTime.Now.Year.ToString(); 获取年份
DateTime.Now.Month.ToString(); 获取月份
DateTime.Now.DayOfWeek.ToString(); 获取星期
DateTime.Now.DayOfYear.ToString(); 获取第几天
DateTime.Now.Hour.ToString(); 获取小时
DateTime.Now.Minute.ToString(); 获取分钟
DateTime.Now.Second.ToString(); 获取秒数
dt.AddYears(n).ToString();
dt.AddDays(n).ToString();
dt.AddHours(n).ToString();
dt.AddMonths(n).ToString();
dt.AddSeconds(n).ToString();
dt.AddMinutes(n).ToString();
2、判断日期大小
public static bool CompareDate(string dateStr1, string dateStr2)
{
DateTime t1 = Convert.ToDateTime(dateStr1);
DateTime t2 = Convert.ToDateTime(dateStr2);
int compNum = DateTime.Compare(t1, t2);
if (compNum > 0)
{
return true;
}
return false;
}
3、计算日期差
方法一
private int DateDiff(DateTime dateStart, DateTime dateEnd)
{
DateTime start = Convert.ToDateTime(dateStart.ToShortDateString());
DateTime end = Convert.ToDateTime(dateEnd.ToShortDateString());
TimeSpan sp = end.Subtract(start);
return sp.Days;
}
方法二
DateTime dt1 = Convert.ToDateTime("2022-03-17 09:49:55.667");
DateTime dt2 = Convert.ToDateTime("2022-03-16 16:51:46.310");
DateTime dt3 = Convert.ToDateTime("2022-04-01 11:00:00.432");
- 使用DateTime相减
TimeSpan ts1 = dt3.Subtract(dt1).Duration();
TimeSpan ts2 = dt3.Subtract(dt2).Duration();
string Days_1 = ts1.Days.ToString();
string Days_2 = ts2.Days.ToString();
- 格式化时间后相减
DateTime Convert_dt1 = Convert.ToDateTime(string.Format("{0}-{1}-{2}", dt1.Year, dt1.Month, dt1.Day));
DateTime Convert_dt2 = Convert.ToDateTime(string.Format("{0}-{1}-{2}", dt2.Year, dt2.Month, dt2.Day));
DateTime Convert_dt3 = Convert.ToDateTime(string.Format("{0}-{1}-{2}", dt3.Year, dt3.Month, dt3.Day));
string Days_3 = (Convert_dt3 - Convert_dt1).Days.ToString();
string Days_4 = (Convert_dt3 - Convert_dt2).Days.ToString();
- 结果显示:
Response.Write("dt3 和 dt1 使用DateTime直接相减 得到天数:" + "<br />");
Response.Write(dt3 + "--------" + dt1 + "相差: " + Days_1 + " 天<br />");
Response.Write("dt3 和 dt2 使用DateTime直接相减 得到天数:" + "<br />");
Response.Write(dt3 + "--------" + dt2 + "相差: " + Days_2 + " 天<br />");
Response.Write("dt3 和 dt1 先格式化后再使用DateTime相减 得到天数:" + "<br />");
Response.Write(dt3 + "--------" + dt1 + "相差: " + Days_3 + " 天<br />");
Response.Write("dt3 和 dt2 先格式化后再使用DateTime相减 得到天数:" + "<br />");
Response.Write(dt3 + "--------" + dt2 + "相差: " + Days_4 + " 天<br />");