public static long earliestLastDay(long endTime, int frequency,
			long lastDay) {
		if (frequency == Appointment.Frequency.ONCE)
		{
			return DateUtil.getStartOfDay(endTime);
		} else if (lastDay == 0)
		{
			return Long.MAX_VALUE;
		} else
		{
			lastDay = DateUtil.getStartOfDay(lastDay);
			switch (frequency)
			{
			case Appointment.Frequency.DAILY:
				return lastDay;
			case Appointment.Frequency.WEEKLY:
				int endTimeFreqHelper = new Date(endTime).getDay();
				int lastDayFreqHelper = new Date(lastDay).getDay();
				int dayDiff = lastDayFreqHelper - endTimeFreqHelper;
				if (dayDiff < 0)
					dayDiff += 7;
				return lastDay - dayDiff * DateUtil.DAY_LENGTH;
			case Appointment.Frequency.MONTHLY:
				endTimeFreqHelper = new Date(endTime).getDate();
				lastDayFreqHelper = new Date(lastDay).getDate();
				dayDiff = lastDayFreqHelper - endTimeFreqHelper;
				if(dayDiff>=0) {
					return lastDay - dayDiff * DateUtil.DAY_LENGTH;
				}
				long monthCursor = prevMonth(getStartOfMonth(lastDay));
				while(countDayInMonth(monthCursor) < endTimeFreqHelper) {
					monthCursor = prevMonth(monthCursor);
				}
				Date rtn = new Date(monthCursor);
				rtn.setDate(endTimeFreqHelper);
				return rtn.getTime();
			default:
				return lastDay;
			}
		}
	}