c# 时间处理帮助类

  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;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值