C# 日月计算不返回C中的预期输出
我想计算两天之间的时差 这是我的代码:C# 日月计算不返回C中的预期输出,c#,datetime,windows-phone-7,C#,Datetime,Windows Phone 7,我想计算两天之间的时差 这是我的代码: private static string CalculateDayMonth(DateTime date1, DateTime date2) { int totalMonth = 0; string returnValue = ""; if (date1 >= date2) { int days = date1.Day - date2.Day; int months = date1.
private static string CalculateDayMonth(DateTime date1, DateTime date2)
{
int totalMonth = 0;
string returnValue = "";
if (date1 >= date2)
{
int days = date1.Day - date2.Day;
int months = date1.Month - date2.Month;
int years = date1.Year - date2.Year;
if (months < 0)
{
months += 12;
years -= 1;
}
if (days < 0)
{
int dayToSubtract = DateTime.DaysInMonth(date2.Year, date2.Month);
days = days + dayToSubtract;
months -= 1;
}
if (years > 0)
totalMonth = years * 12;
else
years = 0;
totalMonth += months;
if (totalMonth <= 0)
returnValue = string.Format(AppResources.Label50414, days.ToString());
else
returnValue = string.Format(AppResources.Label50415, totalMonth.ToString());
}
return returnValue;
}
我的输入日期是:
2015年1月2日14:02:47下午-
2014年12月15日下午16:14:50
预计产量为17天
但实际产量是:18天
我还尝试了其他一些例子。但这也提供了相同的输出
请告诉我哪里出错了。你的代码甚至不能计算你的时、分、秒部分。没有小时部分,基于他们的午夜
但你也会计算小时、分钟和秒数。由于12月15日的时间段比1月2日的时间段要长,因此这两个日期之间的时间差将小于18天。这就是他们不同的原因
看起来你只需要使用简单的like
按格式
Console.WriteLine("{0} days, {1} hours, {2} minutes and {3} seconds",
ts.Days,
ts.Hours,
ts.Minutes,
ts.Seconds); // 17 days, 21 hours, 47 minutes and 57 seconds
这段代码是C。。它对我有用。。。我们还可以了解小时、分钟和秒除了其他,我建议使用我的项目来处理这个问题和其他日期/时间问题。没有必要重新发明轮子:为什么答案是17天?12月15日+17天是1月1日,而不是1月2日。12月有31天……我认为它的计算是正确的。计算12月的天数31-15=16+1月的2天=18。它显示了17天21小时47分钟57分钟seconds@Vijay因为该链接还计算小时部分。您甚至没有在代码中使用/计算日期时间的小时数部分。
Console.WriteLine("{0} days, {1} hours, {2} minutes and {3} seconds",
ts.Days,
ts.Hours,
ts.Minutes,
ts.Seconds); // 17 days, 21 hours, 47 minutes and 57 seconds
private struct DateResult
{
public int years;
public int months;
public int days;
}
private DateResult Date_Difference(DateTime d1, DateTime d2)
{
DateResult d_r;
d_r.years = 0;
d_r.months = 0;
d_r.days = 0;
DateTime frm_date, to_Date;
int key=0;
if (d1 > d2)
{
frm_date = d2;
to_Date = d1;
}
else
{
frm_date = d1;
to_Date = d2;
}
if (frm_date.Day > to_Date.Day) //10 5 //7 24
{
key = month_day[frm_date.Month - 1];
if (key == -1)
{
if (DateTime.IsLeapYear(frm_date.Year))
key = 29;
else
key = 28;
}
}
if (key == 0)
{
d_r.days = to_Date.Day - frm_date.Day;
}
else
{
d_r.days = (to_Date.Day + key) - frm_date.Day;
key = 1;
}
if ((frm_date.Month+key) > to_Date.Month)
{
d_r.months = (to_Date.Month + 12) - (frm_date.Month + key);
key = 1;
}
else
{
d_r.months = to_Date.Month - (frm_date.Month+key);
key=0;
}
d_r.years = to_Date.Year - (frm_date.Year+key);
return d_r;
}