c# 判断时间相等 dateDiff

warning: 这篇文章距离上次修改已过567天,其中的内容可能已经有所变动。

c# 判断时间相等 dateDiff

1..net里没有dateDiff,要对比两个时间还真的很麻烦,一般情况下,datetime中的compare对比的是毫秒级的,想对比s,或d级的,似乎比较麻烦。

以下是对比相等的一个例子,如果是对比大小,还要转换,不好搞,呵呵。

(DateTime.Now.ToShortTimeString() == string.Format("{0}:{1}", cboHour.Text.Trim(), cboMinute.Text.Trim()))

2.在vb里,我们可以很轻松地对比任何时间,dateDiff,能否在.net里也来个dateDiff呢?

  答案是肯定的。下面就是个dateDiff类:

 public sealed class DateTimeManger
    {
        private DateTimeManger()
        { }//end of default constructor
        public static long DateDiff(DateInterval Interval, System.DateTime StartDate, System.DateTime EndDate)
        {
            long lngDateDiffValue = 0;
            System.TimeSpan TS = new System.TimeSpan(EndDate.Ticks - StartDate.Ticks);
            switch (Interval)
            {
                case DateInterval.Second:
                    lngDateDiffValue = (long)TS.TotalSeconds;
                    break;
                case DateInterval.Minute:
                    lngDateDiffValue = (long)TS.TotalMinutes;
                    break;
                case DateInterval.Hour:
                    lngDateDiffValue = (long)TS.TotalHours;
                    break;
                case DateInterval.Day:
                    lngDateDiffValue = (long)TS.Days;
                    break;
                case DateInterval.Week:
                    lngDateDiffValue = (long)(TS.Days / 7);
                    break;
                case DateInterval.Month:
                    lngDateDiffValue = (long)(TS.Days / 30);
                    break;
                case DateInterval.Quarter:
                    lngDateDiffValue = (long)((TS.Days / 30) / 3);
                    break;
                case DateInterval.Year:
                    lngDateDiffValue = (long)(TS.Days / 365);
                    break;
            }
            return (lngDateDiffValue);
        }//end of DateDiff
    }//end of class

喜欢的朋友,可以拿去直接用,呵呵。Q:302777528

none
最后修改于:2023年05月08日 07:55

评论已关闭