Пример #1
0
// difference *this - OtherDate
unsigned long Date::Difference(Date &OtherDate, TimeUnit Unit, bool RoundUp) const {
	unsigned long Result = 0;
	
	switch (Unit) {
		case YEAR:
			Result = Data[YEAR] - OtherDate.Data[YEAR];
			break;
			
		case MONTH:
			Result = (Data[YEAR] - OtherDate.Data[YEAR])*12 + Data[MONTH] - OtherDate.Data[MONTH];
			break;
			
		case DAY:
			if (OtherDate.Data[YEAR] == Data[YEAR]) {
				if (OtherDate.Data[MONTH] == Data[MONTH]) {
					Result = Data[DAY] - OtherDate.Data[DAY];
				} else {
					Result = (OtherDate.DaysInMonth() - OtherDate.Data[DAY]) + Data[DAY];
					
					for (char i=OtherDate.Data[MONTH]+1; i<Data[MONTH]; ++i)
						Result += OtherDate.DaysInMonth(i);
				}
			} else {
				// number of days in the starting year
				Result = OtherDate.DaysInMonth() - OtherDate.Data[DAY];
				for (char i=OtherDate.Data[MONTH]+1; i<=12; ++i)
					Result += OtherDate.DaysInMonth(i);
				
				// number of days in years between the starting and ending years
				for (short i=OtherDate.Data[YEAR]+1; i<Data[YEAR]; ++i)
					Result += IsLeapYear(i) ? 366 : 365;
				
				// number of days in the ending year
				for (char i=1; i<Data[MONTH]; ++i)
					Result += DaysInMonth(i);
				Result += Data[DAY];
			}
			
			break;
			
		case HOUR:
			if (Data[DAY] == OtherDate.Data[DAY]) {
				Result = Data[HOUR] - OtherDate.Data[HOUR];
			} else {
				Result = 24 - OtherDate.Data[HOUR];
				Result += (Difference(OtherDate, DAY, false) - 1) * 24;
				Result += Data[HOUR];
			}
			break;
			
		case MINUTE:
			if (Data[HOUR] == OtherDate.Data[HOUR]) {
				Result = Data[MINUTE] - OtherDate.Data[MINUTE];
			} else {
				Result = 60 - OtherDate.Data[MINUTE];
				Result += (Difference(OtherDate, HOUR, false) - 1) * 60;
				Result += Data[MINUTE];
			}
			break;
			
		case SECOND:
			if (Data[MINUTE] == OtherDate.Data[MINUTE]) {
				Result = Data[SECOND] - OtherDate.Data[SECOND];
			} else {
				Result = 60 - OtherDate.Data[SECOND];
				Result += (Difference(OtherDate, MINUTE, false) - 1) * 60;
				Result += Data[SECOND];
			}
			break;
			
		case WEEK:
			Result = Difference(OtherDate, DAY, false)/7 + 1;
			break;
	}
	
	if (RoundUp == true && Unit < SECOND && Compare(OtherDate, (TimeUnit)(Unit+1)) > 0)
		++Result;
	return Result;
}