public class TimeHelper
{
/// <summary>
/// 获取指定月份最后一天是几号
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public int MounthMaxDay(DateTime date)
{
DateTime d1 = new DateTime(date.Year, date.Month, 1);
DateTime d2 = d1.AddMonths(1).AddDays(-1);
return d2.Day;
}
/// <summary>
/// 在指定日期上加减指定天数后的日期
/// </summary>
/// <param name="date"></param>
/// <param name="dayNum">为负数表示减</param>
/// <returns></returns>
public DateTime AddDays(DateTime date, int dayNum)
{
var newDate = date.AddDays(dayNum);
return newDate;
}
/// <summary>
/// 计算两个日期之间相差的天数,忽略时间的部分
/// </summary>
/// <param name="day1"></param>
/// <param name="day2"></param>
/// <returns></returns>
public int GetDiffDays(DateTime day1, DateTime day2)
{
int diffNum = 0;
day1 = new DateTime(day1.Year, day1.Month, day1.Day);
day2 = new DateTime(day2.Year, day2.Month, day2.Day);
diffNum = (int)(day1 - day2).TotalDays;
return diffNum;
}
/// <summary>
/// 获取相差多少天,时,分,秒的字符串
/// </summary>
/// <param name="day1"></param>
/// <param name="day2"></param>
/// <returns></returns>
public string GetDiffTimeStr(DateTime day1, DateTime day2)
{
string timeStr = "";
double seconds = (day1 - day2).TotalSeconds;
int day = (int)seconds / (24 * 3600);
int hour = (int)(seconds - day * 24 * 3600) / (60 * 60);
int min = (int)(seconds - day * 24 * 3600 - hour * 3600) / 60;
int s = (int)(seconds - day * 24 * 3600 - hour * 3600 - min * 60);
timeStr = day + "天" + hour + "时" + min + "分" + s + "秒";
return timeStr;
}
/// <summary>
/// 获取指定日期是星期几
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public string GetWeek(DateTime date)
{
//获取今天是星期几
string[] Day = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
string week = Day[Convert.ToInt32(date.DayOfWeek.ToString("d"))].ToString();
return week;
}
}
c# 时间处理帮助类
最新推荐文章于 2024-08-12 09:28:18 发布