在 C# 中比较两个日期并计算差异

Posted

技术标签:

【中文标题】在 C# 中比较两个日期并计算差异【英文标题】:Compare two dates in C# and calculate the difference 【发布时间】:2014-12-20 12:12:24 【问题描述】:

我有两个日期第一个是nowDate 12/20/2014 5:19:31 PM,第二个是messageTime 12/20/2014 1:14:12 PM 我想比较这些日期并计算结果并显示给用户,它计算现在时间和消息日期之间的时间差我的代码是

// Last Message Time
DateTime messageTime = Convert.ToDateTime(lastMessageTime);

int msgYear = messageTime.Year;
int msgMonth = messageTime.Month;
int msgDay = messageTime.Day;
int msgHour = messageTime.Hour;
int msgMinute = messageTime.Minute;

//Current Date Time
DateTime nowDate = DateTime.Now;

// TimeSpan difference = nowDate.Subtract(messageTime);
int nowYear = nowDate.Year;
int nowMonth = nowDate.Month;
int nowDay = nowDate.Day;
int nowHour = nowDate.Hour;
int nowMinute = nowDate.Minute;

if (msgYear == nowYear)

    if (msgMonth == nowMonth)
    
        if (msgDay == nowDay)
        
            if (msgHour == nowHour)
            
                if (msgMinute == nowMinute)
                
                    lastMessageTime = "Just Now";
                
                else
                
                    if (nowMinute - msgMinute == 1)
                        lastMessageTime = "1 minute ago";
                    else
                        lastMessageTime = nowMinute - msgMinute + " minutes ago";
                
            
            else
            
                if (nowHour - msgHour == 1)
                   lastMessageTime = "1 hour ago";
                else
                   lastMessageTime = nowHour - msgHour + " hours ago";
            
        
        else
        
            if (nowDay - msgDay == 1)
               lastMessageTime = "1 Day ago";
            else
               lastMessageTime = nowDay - msgDay + " days ago";
        
    
    else
    
        if (nowMonth - msgMonth == 1)
           lastMessageTime = "1 month ago";
        else
           lastMessageTime = nowMonth - msgMonth + " months ago";
    

else

    if (nowYear - msgYear == 1)
       lastMessageTime = "1 year ago";
    else
       lastMessageTime = nowYear - msgYear + " years ago";

但是这段代码有问题。假设最后一条消息时间是12/20/2014 05:59:31 PM,当前时间是12/20/2014 06:00:31 PM它显示结果为1 hour ago,但实际差异是1分钟左右,请帮助某人

【问题讨论】:

如果你减去两个日期,d1-d2,你会得到一个时间跨度,这就是你想要的。 .Net 允许您像数字一样对日期时间进行算术运算,但是,结果将是 TimeSpan 类型。然后,您可以通过其中一个属性找出总差异。不要重新发明***和过度设计。 【参考方案1】:

您的代码似乎很复杂。

当你想比较DateTime的,你可以使用<>操作符。您可以使用- 运算符来获得它们的区别。

DateTime messageTime = Convert.ToDateTime(lastMessageTime);
DateTime nowDate = DateTime.Now;
TimeSpan diff;

if(messageTime > nowDate)
   diff = messageTime - nowDate;
if(messageTime < nowDate)
   diff = nowDate - messageTime ;

您可以使用TimeSpan properties 来获取不同的分钟、小时、天等。

Console.WriteLine (diff.Minutes);
Console.WriteLine (diff.Hours);
Console.WriteLine (diff.Days);

还相关:Calculate relative time in C#

【讨论】:

使用 TimeSpan,您将停留在 TotalDays。如果他们想要 TotalYears(例如,smbdy 几岁?) - 您需要使用特定的日期部分(由于闰年,您永远不知道总天数在总年数中的含义) @CharanGhate 这是一个伪代码。更新了我的答案。 @Soner Gönül 它可以工作,但我如何使用此代码计算月份和年份? 会报错,代码应该是TimeSpan diff = TimeSpan.Zero; @CharanGhate 阅读此内容:***.com/questions/1525990/… 同样的方法也适用于 Year。【参考方案2】:

您可以编写自己的代码,但请查看humaninzer:http://www.hanselman.com/blog/NuGetPackageOfTheWeekHumanizerMakesNETDataTypesMoreHuman.aspx

要自己做,您应该使用 TimeSpan 类。当您添加或减去两个日期时,您会得到一个 TimeSpan 请参阅 Soner 提供的示例

【讨论】:

【参考方案3】:

我有答案 :)

 private void getDifference_Click(object sender, EventArgs e)
    
        DateTime messageTime = Convert.ToDateTime("02/20/2013 6:21:12 PM");
        DateTime nowDate = DateTime.Now;
        TimeSpan diff = TimeSpan.Zero;

        if (messageTime > nowDate)
            diff = messageTime - nowDate;
        if (messageTime < nowDate)
            diff = nowDate - messageTime;

        int intSeconds = diff.Seconds;
        int intMinutes = diff.Minutes;
        int intDays = diff.Days;
        int intMonths = 0;
        int intYear = 0;
        if (intDays > 31)
        
            intMonths = MonthDifference(nowDate, messageTime);
        
        if (intMonths > 12)
        
            string strYear = Convert.ToString(intMonths / 12);
            string[] strParts = strYear.Split('.');
            intYear = Convert.ToInt32(strParts[0].ToString());
        
        string lastMessageTime = "";
        if (intYear == 0)
        
            if (intMonths == 0)
            
                if (intDays == 0)
                
                    if (intMinutes == 0)
                    
                        lastMessageTime = "just now";
                    
                    else
                    
                        if (intMinutes == 1)
                            lastMessageTime = "1 minute ago";
                        else
                            lastMessageTime = intMinutes + " minutes ago";
                    
                
                else
                
                    if (intDays == 1)
                        lastMessageTime = "1 day ago";
                    else
                        lastMessageTime = intDays + " days ago";
                
            
            else
            
                if (intMonths == 1)
                    lastMessageTime = "1 month ago";
                else
                    lastMessageTime = intMonths + " months ago";
            
        
        else
        
            if (intYear == 1)
                lastMessageTime = "1 year ago";
            else
                lastMessageTime = intYear + " years ago";
        


    
    public int MonthDifference(DateTime nowDate, DateTime messageTime)
    
        return (nowDate.Month - messageTime.Month) + 12 * (nowDate.Year - messageTime.Year);
    

【讨论】:

以上是关于在 C# 中比较两个日期并计算差异的主要内容,如果未能解决你的问题,请参考以下文章

计算两个 Java 日期实例之间的差异

C#比较存储在XML文件中的两个日期时间

在 Swift 中计算两个日期之间的差异

Android比较纪元时间和今天日期并输出差异[重复]

如何在java中计算两个日期之间的年龄或差异

比较两个表中的值并计算它们的差异