【发布时间】:2010-12-24 07:41:09
【问题描述】:
我想使用 30 天的月份从日期时间对象中减去时间跨度,忽略闰年等。
Date is 1983/5/1 13:0:0 (y/m/d-h:m:s)
Time span is 2/4/28-2:51:0 (y/m/d-h:m:s)
我可以使用 DateTime 和 TimeSpan 对象来执行此操作,将时间跨度的年和月转换为天(假设一个月为 30 天,一年为 ~364 天)。
new DateTime(1981,5,1,13,0,0).Subtract(new TimeSpan(878,13,51,0));
这样我得到了结果:
{12/4/1978 11:09:00 PM}
上面的答案显然没有忽略我想要忽略的因素,并给了我一个准确的答案。但在这种情况下,这不是我想要的,所以我写了下面的代码。
public static CustomDateTime operator -(CustomDateTime DT1,CustomDateTime DT2)
{
CustomDateTime retVal = new CustomDateTime();
try
{
const int daysPerYear = 364.25;
const int monthsPerYear = 12;
const int daysPerMonth = 30;
const int hoursPerDay = 24;
const int minutesPerHour = 60;
retVal.Minute = DT1.Minute - DT2.Minute;
if (retVal.Minute < 0)
{
retVal.Minute += minutesPerHour;
DT1.Hour -= 1;
}
retVal.Hour = DT1.Hour - DT2.Hour;
if (retVal.Hour < 0)
{
retVal.Hour += hoursPerDay;
DT1.Day -= 1;
}
retVal.Day = DT1.Day - DT2.Day;
if (retVal.Day < 0)
{
retVal.Day += daysPerMonth;
DT1.Month -= 1;
}
retVal.Month = DT1.Month - DT2.Month;
if (retVal.Month < 0)
{
retVal.Month += monthsPerYear;
DT1.Year -= 1;
}
retVal.Year = DT1.Year - DT2.Year;
}
catch (Exception ex) { }
return retVal;
}
然后我得到:
1981/0/3-10:9:0
这与我所追求的非常接近,除了我不应该得到 0 月份和年份应该是 1980 年。感谢任何形式的帮助。
只是为了再次说明问题;在这种情况下,我必须使用 30 天的月份并忽略闰年、不同的月份等。我知道这是一件很奇怪的事情。因此,我非常喜欢“错误答案”,而不是托管类给出的确切答案。
【问题讨论】:
-
“如果我手动执行此操作”是什么意思?
-
我相信它的意思是“手工,在纸上”。而且我不知道他所说的“原生类”是什么意思。
-
是的。从分钟(m2)中减去分钟(m1)。如果 m1
-
“假设一个月有 30 天”?你怎么能这样假设?
-
@yodaj007 我的意思是 .Net 框架中的 DateTime 对象。如果我的描述在技术上不正确,请见谅。