gpt4 book ai didi

c# - 在C#中比较两个日期并计算差值

转载 作者:太空宇宙 更新时间:2023-11-03 18:28:44 24 4
gpt4 key购买 nike

我有两个日期,第一个是 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 小时前 但实际差异是 1 分钟之类的,请帮助某人

最佳答案

你的代码看起来很复杂。

当你想比较时DateTime的,你可以使用 <>运算符(operator)。你可以使用 -运营商得到他们的区别。

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#

关于c# - 在C#中比较两个日期并计算差值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27580114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com