C#计算时间差值

如下。计算两个时间差值、判断是几分钟前。几小时前。或者几天前。

	///<summary>时间</summary>
    public class TimeParser
    {
        /// <summary>
        /// 把秒转换成分钟
        /// </summary>
        /// <returns></returns>
        public static int SecondToMinute(int Second)
        {
            decimal mm = (decimal)((decimal)Second / (decimal)60);
            return Convert.ToInt32(Math.Ceiling(mm));
        }

        #region 返回某年某月最后一天
        /// <summary>
        /// 返回某年某月最后一天
        /// </summary>
        /// <param name="year">年份</param>
        /// <param name="month">月份</param>
        /// <returns>日</returns>
        public static int GetMonthLastDate(int year, int month)
        {
            DateTime lastDay = new DateTime(year, month, new System.Globalization.GregorianCalendar().GetDaysInMonth(year, month));
            int Day = lastDay.Day;
            return Day;
        }
        #endregion

        #region 返回时间差
        public static string DateDiff(DateTime DateTime1, DateTime DateTime2)
        {
            string dateDiff = null;
            try
            {
                //TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
                //TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
                //TimeSpan ts = ts1.Subtract(ts2).Duration();
                TimeSpan ts = DateTime2 - DateTime1;
                if (ts.Days >= 1)
                {
					if(ts.Days <= 20)
					{
						dateDiff =string.Concat(ts.Days.ToString(),"天前");
					}
					else
					{
						StringBuilder sb = new StringBuilder(DateTime1.Month.ToString());
						sb.Append("月");
						sb.Append(DateTime1.Day.ToString());
						sb.Append("日");
						dateDiff = sb.ToString();
					}
                }
                else
                {
                    if (ts.Hours > 1)
                    {
                        dateDiff =string.Concat(ts.Hours.ToString(),"小时前");
                    }
                    else
                    {
                        dateDiff = string.Concat(ts.Minutes.ToString(), "分钟前");
                    }
                }
            }
            catch
            { }
            return dateDiff;
        }
        #endregion
    }

 

本文链接:

https://www.bobsong.net/167.html
1 + 3 =
快来做第一个评论的人吧~