/// <summary> /// ��������ʱ��� /// </summary> /// <param name="interval">ָ�����</param> /// <param name="StartDate">��ʼʱ��</param> /// <param name="EndDate">����ʱ��</param> /// <returns></returns> public static long DateDiff(DateTimeInterval interval, DateTime StartDate,DateTime EndDate) { long lngDateDiffValue = 0; TimeSpan TS = new System.TimeSpan(EndDate.Ticks - StartDate.Ticks); switch (interval) { case DateTimeInterval.Day: lngDateDiffValue = (long)TS.Days; break; case DateTimeInterval.Hour: lngDateDiffValue = (long)TS.TotalHours; break; case DateTimeInterval.Minute: lngDateDiffValue = (long)TS.TotalMinutes; break; case DateTimeInterval.Month: lngDateDiffValue = (long)(TS.Days / 30); break; case DateTimeInterval.Quarter: lngDateDiffValue = (long)((TS.Days / 30) / 3); break; case DateTimeInterval.Second: lngDateDiffValue = (long)TS.TotalSeconds; break; case DateTimeInterval.Week: lngDateDiffValue = (long)(TS.Days / 7); break; case DateTimeInterval.Year: lngDateDiffValue = (long)(TS.Days / 365); break; } return (lngDateDiffValue); }
public void UpdateDateTimeInterval(DateTimeInterval dateTimeImterval) { // TODO refactor me var updatingItem = db.DateTimeIntervals.Single(interval => interval.Id == dateTimeImterval.Id); updatingItem.StartDate = dateTimeImterval.StartDate; updatingItem.EndDate = dateTimeImterval.EndDate; updatingItem.HeatSupplier = dateTimeImterval.HeatSupplier; }
internal static bool HasAllTheseIntervals(this long ticks, DateTimeInterval intervals) { bool result = true; foreach (Enum flag in intervals.GetFlags(SortOrder.Descending)) { result &= ticks.HasInterval((DateTimeInterval)flag); } return(result); }
public void IsSinglePointInterval_NonSinglePoint() { // Arrange var(start, end) = Fixture.Create <LocalDateTime>((x, y) => x < y); var interval = new DateTimeInterval(start, end); // Act var isSinglePointInterval = interval.IsSinglePointInterval(); // Assert isSinglePointInterval.Should().BeFalse(); }
public void IsSinglePointInterval_SinglePoint() { // Arrange var localDateTime = Fixture.Create <LocalDateTime>(); var interval = new DateTimeInterval(localDateTime, localDateTime); // Act var isSinglePointInterval = interval.IsSinglePointInterval(); // Assert isSinglePointInterval.Should().BeTrue(); }
private void AddGageHeightMeasurements(DateTimeInterval measurementInterval, DischargeActivity dischargeActivity) { var startGageHeight = new Measurement(_fieldVisit.DischargeActivity.StartGageHeight, _fieldVisit.UnitSystem.DistanceUnitId); var endGageHeight = new Measurement(_fieldVisit.DischargeActivity.EndGageHeight, _fieldVisit.UnitSystem.DistanceUnitId); dischargeActivity.GageHeightMeasurements.Add(new GageHeightMeasurement(startGageHeight, measurementInterval.Start)); dischargeActivity.GageHeightMeasurements.Add(new GageHeightMeasurement(endGageHeight, measurementInterval.End)); }
private static DateTimeInterval ExpandInterval(DateTimeInterval interval, DateTimeOffset startTime, DateTimeOffset endTime) { var minStart = interval.Start < startTime ? interval.Start : startTime; var maxEnd = interval.End > endTime ? interval.End : endTime; return(new DateTimeInterval(minStart, maxEnd)); }
public void Construction_EqualStartAndEnd() { // Arrange var localDateTime = Fixture.Create <LocalDateTime>(); // Act var interval = new DateTimeInterval(localDateTime, localDateTime); // Assert interval.Start.Should().Be(localDateTime); interval.End.Should().Be(localDateTime); }
internal void IncreaseViewDates(DateTimeInterval interval) { this.scheduler.SelectedTimeSlot = this.scheduler.SelectedTimeSlot.AddInterval(interval); if (interval.Months == 0) { this.StartDate = this.StartDate.AddInterval(interval); } else { this.StartDate = this.GetStartDateForViewDefinition(this.activeViewDefinition, this.scheduler.SelectedTimeSlot.Start); } }
public void Construction_Properties() { // Arrange var(start, end) = Fixture.Create <LocalDateTime>((x, y) => x < y); // Act var interval = new DateTimeInterval(start, end); // Assert interval.Start.Should().Be(start); interval.End.Should().Be(end); }
private DischargeActivity CreateDischargeActivityWithSummary(DateTimeInterval observationInterval, UnitSystem unitSystem) { var factory = new DischargeActivityFactory(unitSystem); var dischargeActivity = factory.CreateDischargeActivity(observationInterval, _parsedData.TotalDischarge); dischargeActivity.Party = _parsedData.UserId; AddGageHeights(dischargeActivity, observationInterval, unitSystem); return(dischargeActivity); }
public void Overlaps_LongerThanADay_True(Period period) { // Arrange var startDateTime = Fixture.Create <LocalDateTime>(); var dateTimeInterval = new DateTimeInterval(startDateTime, period); var timeInterval = Fixture.Create <TimeInterval>(); // Act var overlaps = timeInterval.Overlaps(dateTimeInterval); // Assert overlaps.Should().BeTrue(); }
internal void DecreaseViewDates(DateTimeInterval interval) { this.scheduler.SelectedTimeSlot = this.scheduler.SelectedTimeSlot.SubtractInterval(interval); if (interval.Months == 0 || (this.activeViewDefinition is TimelineViewDefinition && interval.Months > 0 && interval.Days == 0)) { this.StartDate = this.StartDate.SubtractInterval(interval); } else { this.StartDate = this.GetStartDateForViewDefinition(this.activeViewDefinition, this.scheduler.SelectedTimeSlot.Start); } }
public void StringRepresentation() { // Arrange var start = new LocalDateTime(2000, 1, 1, 09, 59, 33); var end = new LocalDateTime(2001, 6, 19, 13, 11, 42); var interval = new DateTimeInterval(start, end); // Act var s = interval.ToString(); // Assert s.Should().Be("2000-01-01T09:59:33/2001-06-19T13:11:42"); }
public void ToTimeInterval_LongerThanADay_ThrowsException() { // Arrange var startDateTime = Fixture.Create <LocalDateTime>(); var period = Period.FromDays(1) + Period.FromNanoseconds(1); var interval = new DateTimeInterval(startDateTime, period); // Act Action act = () => interval.ToTimeInterval(); // Assert act.Should().Throw <NotSupportedException>().And.Message.Should().Contain(nameof(interval)); }
/// <summary> Resolves interval for specified datetime. </summary> public static DateTime ResolveInterval(this DateTime input, DateTimeInterval interval) { DateTime output = input; // Resolve output = output.AddYears(interval.Years); output = output.AddMonths(interval.Months); output = output.AddDays(interval.Days); output = output.AddHours(interval.Hours); output = output.AddMinutes(interval.Minutes); return(output); }
public void InZone_NullDateTimeInterval_ThrowsException() { // Arrange DateTimeInterval dateTimeInterval = null; var timeZone = Fixture.Create <DateTimeZone>(); // Act Action act = () => dateTimeInterval.InZone(timeZone); // Assert act.Should().Throw <ArgumentNullException>() .WithMessage("Value cannot be null.\r\nParameter name: dateTimeInterval"); }
private DischargeActivity CreateExpectedDischargeActivity() { var startTime = new DateTimeOffset(_gaugingSummaryItem.StartDate, LocationUtcOffset); var endTime = new DateTimeOffset(_gaugingSummaryItem.EndDate, LocationUtcOffset); var surveyPeriod = new DateTimeInterval(startTime, endTime); var discharge = new Measurement(_gaugingSummaryItem.Flow.GetValueOrDefault(), ParametersAndMethodsHelper.UnitSystem.DischargeUnitId); return(new DischargeActivity(surveyPeriod, discharge) { Party = _gaugingSummaryItem.ObserversName, MeasurementId = _gaugingSummaryItem.GaugingId.ToString(NumberFormatInfo.InvariantInfo) }); }
public void Overlap_Overlaps_Overlap() { // Arrange var(first, second) = Fixture.Create <DateTimeInterval>((x, y) => x.Start < y.Start && y.Start < x.End && x.End < y.End); var expectedOverlap = new DateTimeInterval(second.Start, first.End); // Act var overlap = first.GetOverlapWith(second); var overlapInverted = second.GetOverlapWith(first); // Assert overlap.Should().Be(expectedOverlap); overlapInverted.Should().Be(expectedOverlap); }
public void Overlap_Meets_Null() { // Arrange var(first, dateTime) = Fixture.Create <DateTimeInterval, LocalDateTime>((x, y) => x.End < y); var second = new DateTimeInterval(first.End, dateTime); // Act var overlap = first.GetOverlapWith(second); var overlapInverted = second.GetOverlapWith(first); // Assert overlap.Should().BeNull(); overlapInverted.Should().BeNull(); }
public void Equals_EqualValues() { // Arrange var(start, end) = Fixture.Create <LocalDateTime>((x, y) => x < y); var interval1 = new DateTimeInterval(start, end); var interval2 = new DateTimeInterval(start, end); // Assert interval1.Should().Be(interval2); interval1.GetHashCode().Should().Be(interval2.GetHashCode()); (interval1 == interval2).Should().BeTrue(); (interval1 != interval2).Should().BeFalse(); interval1.Equals(interval2).Should().BeTrue(); // IEquatable implementation }
internal static FishingRecord GetFishingRecord2() { DateTime dtAdded = new DateTime(2014, 1, 11, 14, 23, 12); DateTimeInterval dtInterval = new DateTimeInterval(new DateTime(2013, 9, 15, 14, 00, 00), new DateTime(2013, 9, 15, 18, 00, 00)); Location location = new Location("Medulin", new Coordinates(3, 4), 23, ""); NatureEvents context = new NatureEvents(Winds.N, MoonPhases.fullMoon, Tides.waterRising); FishCatch fishCatch = new FishCatch(); fishCatch.AddCatch("brancin", 4.5); fishCatch.AddCatch("tuna", 10.0); fishCatch.AddSale("tuna", 10.0, 500.0); return(new FishingRecord(dtAdded, dtInterval, location, context, fishCatch)); }
private ManualGaugingDischargeSection CreateDischargeSectionWithDescription(UnitSystem unitSystem, DateTimeInterval observationInterval) { var factory = new ManualGaugingDischargeSectionFactory(unitSystem); var manualGaugingDischarge = factory.CreateManualGaugingDischargeSection(observationInterval, _parsedData.TotalDischarge); //Party: manualGaugingDischarge.Party = _parsedData.UserId; //Discharge Method should always be Mid Section, i.e., points are rendered in the middle of a segment on UI. manualGaugingDischarge.DischargeMethod = DischargeMethodType.MidSection; return(manualGaugingDischarge); }
private static DischargeActivity CreateDischargeActivity(GaugingSummaryItem gaugingSummary, TimeSpan locationTimeZoneOffset) { var startTime = new DateTimeOffset(gaugingSummary.StartDate, locationTimeZoneOffset); var endTime = new DateTimeOffset(gaugingSummary.EndDate, locationTimeZoneOffset); var surveyPeriod = new DateTimeInterval(startTime, endTime); var discharge = gaugingSummary.Flow.AsDischargeMeasurement(); return(new DischargeActivity(surveyPeriod, discharge) { Party = gaugingSummary.ObserversName, MeasurementId = GenerateMeasurementId(gaugingSummary), MeanIndexVelocity = GetMeanIndexVelocity(gaugingSummary) }); }
/// <summary> /// this method returns parcels by account in Period. This method compares the beginDate/endDate /// to DueDate and OperationDate /// </summary> /// <param name="companyId"></param> /// <param name="accountId"></param> /// <param name="beginDate"></param> /// <param name="endDate"></param> /// <returns></returns> public IQueryable <Parcel> GetParcelsByAccountInPeriod(int companyId, int accountId, DateTimeInterval dateTimeInterval) { IQueryable <Parcel> query = from parcel in GetParcelsByAccount(companyId, accountId) where (parcel.DueDate > dateTimeInterval.BeginDate && parcel.DueDate < dateTimeInterval.EndDate) || (parcel.OperationDate > dateTimeInterval.BeginDate && parcel.OperationDate < dateTimeInterval.EndDate) select parcel; return(query); }
public void InZone_SinglePointDateTimeInterval_SinglePointInterval() { // Arrange var dateTime = Fixture.Create <LocalDateTime>(); var dateTimeInterval = new DateTimeInterval(dateTime, dateTime); var timeZone = new FixedOffsetDateTimeZone(Offset.FromHours(3)); // Act var interval = dateTimeInterval.InZone(timeZone); // Assert interval.Start.Should().Be(interval.End); interval.Start.Should().Be(timeZone.AtLeniently(dateTime).ToInstant()); }
public void Overlaps_Starts_True() { // Arrange var(first, dateTime) = Fixture.Create <DateTimeInterval, LocalDateTime>((x, y) => x.End < y); var second = new DateTimeInterval(first.Start, dateTime); // Act var overlaps = first.Overlaps(second); var overlapsInverted = second.Overlaps(first); // Assert overlaps.Should().BeTrue(); overlapsInverted.Should().BeTrue(); }
public void Overlap_DifferentCalendars_ThrowsException() { // Arrange var first = Fixture.Create <DateTimeInterval>(); var(start, end) = Fixture.Create <LocalDateTime>((x, y) => x <= y); var second = new DateTimeInterval(start.WithCalendar(CalendarSystem.Julian), end.WithCalendar(CalendarSystem.Julian)); // Act Action act = () => first.GetOverlapWith(second); // Assert act.Should().ThrowExactly <ArgumentException>().WithMessage("The given interval must be in the same calendar as this interval.\r\nParameter name: second"); }
public void Overlaps_Finishes_True() { // Arrange var(dateTime, first) = Fixture.Create <LocalDateTime, DateTimeInterval>((d, i) => d < i.Start); var second = new DateTimeInterval(dateTime, first.End); // Act var overlaps = first.Overlaps(second); var overlapsInverted = second.Overlaps(first); // Assert overlaps.Should().BeTrue(); overlapsInverted.Should().BeTrue(); }
// ReSharper disable once InconsistentNaming public void Test_interval_starts_within_allowed_interval_and_ends_after_it() { DateTime now = DateTime.Now; DateTimeInterval testInterval = new DateTimeInterval { From = now.AddDays(1), To = now.AddDays(30) }; DateTimeInterval allowedInterval = new DateTimeInterval { From = now, To = now.AddDays(6) }; DateTimeInterval result = DateTimeUtils.GetIntervalIntersection(testInterval, allowedInterval); Assert.AreEqual(now.AddDays(1), result.From); Assert.AreEqual(now.AddDays(6), result.To); }
// ReSharper disable once InconsistentNaming public void Test_interval_equals_the_allowed_interval() { DateTime now = DateTime.Now; DateTimeInterval testInterval = new DateTimeInterval { From = now, To = now.AddDays(6) }; DateTimeInterval allowedInterval = new DateTimeInterval { From = now, To = now.AddDays(6) }; DateTimeInterval result = DateTimeUtils.GetIntervalIntersection(testInterval, allowedInterval); Assert.AreEqual(now, result.From); Assert.AreEqual(now.AddDays(6), result.To); }
// ReSharper disable once InconsistentNaming public void Result_should_be_empty_when_there_is_no_intersection_because_test_interval_is_after_allowed_interval() { DateTime now = DateTime.Now; DateTimeInterval testInterval = new DateTimeInterval { From = now.AddDays(10), To = now.AddDays(5) }; DateTimeInterval allowedInterval = new DateTimeInterval { From = now, To = now.AddDays(3) }; DateTimeInterval result = DateTimeUtils.GetIntervalIntersection(testInterval, allowedInterval); Assert.IsNull(result.From); Assert.IsNull(result.To); }
/// <summary> /// same common params similar to the VBScript DateDiff: /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/vsfctdatediff.asp /// /* /// * Sample Code: /// * System.DateTime dt1 = new System.DateTime(1974,12,16); /// * System.DateTime dt2 = new System.DateTime(1973,12,16); /// * double diff = DateDiff(DateTimeInterval.Day, dt1, dt2); /// * /// */ /// </summary> /// <param name="howtocompare"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <returns></returns> //adapted from http://authors.aspalliance.com/nothingmn/default.aspx?whichpoll=nothingmn_117&aid=117 public static double DateDiff(DateTimeInterval howtocompare, System.DateTime startDate, System.DateTime endDate) { double diff=0; try { System.TimeSpan TS = new System.TimeSpan(startDate.Ticks-endDate.Ticks); switch (howtocompare) { case DateTimeInterval.Tick: diff = Convert.ToDouble(TS.Ticks); break; case DateTimeInterval.Millisecond: diff = Convert.ToDouble(TS.TotalMilliseconds); break; case DateTimeInterval.Second: diff = Convert.ToDouble(TS.TotalSeconds); break; case DateTimeInterval.Minute: diff = Convert.ToDouble(TS.TotalMinutes); break; case DateTimeInterval.Hour: diff = Convert.ToDouble(TS.TotalHours); break; case DateTimeInterval.Day: diff = Convert.ToDouble(TS.TotalDays); break; case DateTimeInterval.Week: diff = Convert.ToDouble(TS.TotalDays/7); break; case DateTimeInterval.Fortnight: diff = Convert.ToDouble(TS.TotalDays/15); break; case DateTimeInterval.Month: diff = Convert.ToDouble((TS.TotalDays/365)/12); break; case DateTimeInterval.Quarter: diff = Convert.ToDouble((TS.TotalDays/365)/4); break; case DateTimeInterval.Year: diff = Convert.ToDouble(TS.TotalDays/365); break; } } catch { diff = -1; } return diff; }
/// <summary> /// Gets the time. /// </summary> /// <param name="date">The date.</param> /// <param name="calendar">The calendar.</param> /// <returns>System.Nullable{DateTime}.</returns> private static DateTime? GetTime(DateTime date, ICalendar calendar) { if (calendar == null || calendar.WorkingIntervals == null || !calendar.WorkingIntervals.Any()) { return date; } var day = date.DayOfWeek; var skipInterval = false; foreach (var item in calendar.WorkingIntervals.OrderBy(x => x.StartDate).Where(x => x.Weekday == day.ToString())) { if (!item.StartDate.HasValue) continue; if (calendar.WorkingExceptions != null) { var startDate = new DateTime(date.Year, date.Month, date.Day, item.StartDate.Value.Hour, item.StartDate.Value.Minute, 0); var finishDateHour = 0; var finishDateMinute = 0; if (item.FinishDate != null) { finishDateHour = item.FinishDate.Value.Hour; finishDateMinute = item.FinishDate.Value.Minute; } var finishDate = new DateTime(date.Date.Year, date.Date.Month, date.Date.Day, finishDateHour, finishDateMinute, 0); var workingInterval = new DateTimeInterval(startDate, finishDate); var intersectedExceptions = new List<DateTimeInterval>(); foreach (var exception in calendar.WorkingExceptions) { if (exception.StartDate.HasValue && exception.FinishDate.HasValue) { var compareResult = workingInterval.Compare(exception.StartDate.Value, exception.FinishDate.Value); switch (compareResult) { case Interposition.Inside: skipInterval = true; break; case Interposition.IntersectRight: case Interposition.IntersectLeft: case Interposition.Contains: intersectedExceptions.Add(new DateTimeInterval(exception.StartDate.Value, exception.FinishDate.Value)); break; } } if (skipInterval) break; } if (intersectedExceptions.Count > 0) { for (var i = 0; i < intersectedExceptions.Count; i++) { //объеденить пересекающиеся между собой исключения for (var j = i + 1; j < intersectedExceptions.Count; j++) { var uniteResult = intersectedExceptions[i].Unite(intersectedExceptions[j]); if (uniteResult != null) { //remove united items intersectedExceptions.Remove(intersectedExceptions[j]); intersectedExceptions.Remove(intersectedExceptions[i]); //insert united result instead intersectedExceptions.Insert(i, uniteResult); } } } // единственное исключение с которым осталось сравнить рабочее время. var resultException = intersectedExceptions.OrderBy(exc => exc.StartDate).First(); switch (workingInterval.Compare(resultException)) { case Interposition.Inside: skipInterval = true; break; case Interposition.IntersectRight: return resultException.FinishDate; default: return workingInterval.StartDate; } } } if (skipInterval == false) return date.Date + item.StartDate.Value.TimeOfDay; skipInterval = false; } return null; }
private static ICalendarWorkingException GetWorkingException(DateTime date, ICalendar calendar, List<ICalendarWorkingInterval> workingIntervals, FrequencyPatternType pattern = FrequencyPatternType.Monthly) { if (calendar == null || !calendar.WorkingExceptions.Any() || workingIntervals == null || !workingIntervals.Any()) return null; foreach (var item in workingIntervals) { if (!item.StartDate.HasValue) continue; var startDate = new DateTime(date.Year, date.Month, date.Day, item.StartDate.Value.Hour, item.StartDate.Value.Minute, 0); var finishDateHour = 0; var finishDateMinute = 0; if (item.FinishDate.HasValue) { finishDateHour = item.FinishDate.Value.Hour; finishDateMinute = item.FinishDate.Value.Minute; } var finishDate = new DateTime(date.Date.Year, date.Date.Month, date.Date.Day, finishDateHour, finishDateMinute, 0); var workingInterval = new DateTimeInterval(startDate, finishDate); foreach (var exception in calendar.WorkingExceptions.Where(x => x.StartDate.HasValue && x.FinishDate.HasValue && (x.FinishDate.Value > x.StartDate.Value))) { var compareResult = workingInterval.Compare(exception.StartDate.Value, exception.FinishDate.Value); switch (compareResult) { case Interposition.Inside: case Interposition.IntersectRight: case Interposition.IntersectLeft: return pattern == FrequencyPatternType.Daily ? null : exception; case Interposition.Contains: return exception; } } } return null; }
public void InsertDateTimeInterval(DateTimeInterval dateTimeImterval) { db.DateTimeIntervals.AddObject(dateTimeImterval); }
DateTime DateTimeFloorCeiling(DateTime dt, DateTimeInterval interval, int increment, bool isCeiling) { DateTime dtNew = dt; switch (interval) { case DateTimeInterval.Second: if (dt.Millisecond != 0 || dt.Second % increment != 0) { dtNew = dtNew.AddMilliseconds(-dt.Millisecond); dtNew = dtNew.AddSeconds(-dt.Second % increment); if (isCeiling) dtNew = dtNew.AddSeconds(increment); } break; case DateTimeInterval.Minute: if (dt.Millisecond != 0 || dt.Second != 0 || dt.Minute % increment != 0) { dtNew = dtNew.AddMilliseconds(-dt.Millisecond); dtNew = dtNew.AddSeconds(-dt.Second); dtNew = dtNew.AddMinutes(-dt.Minute % increment); if (isCeiling) dtNew = dtNew.AddMinutes(increment); } break; case DateTimeInterval.Hour: if (dt.Millisecond != 0 || dt.Second != 0 || dt.Minute != 0 || dt.Hour % increment != 0) { dtNew = dtNew.AddMilliseconds(-dt.Millisecond); dtNew = dtNew.AddSeconds(-dt.Second); dtNew = dtNew.AddMinutes(-dt.Minute); dtNew = dtNew.AddHours(-dt.Hour % increment); if (isCeiling) dtNew = dtNew.AddHours(increment); } break; case DateTimeInterval.Day: if (dt.Millisecond != 0 || dt.Second != 0 || dt.Minute != 0 || dt.Hour != 0 || (dt.Day - 1) % increment != 0) { dtNew = dtNew.AddMilliseconds(-dt.Millisecond); dtNew = dtNew.AddSeconds(-dt.Second); dtNew = dtNew.AddMinutes(-dt.Minute); dtNew = dtNew.AddHours(-dt.Hour); dtNew = dtNew.AddDays(-((dt.Day - 1) % increment)); if (isCeiling) dtNew = dtNew.AddDays(increment); } break; case DateTimeInterval.Month: if (dt.Millisecond != 0 || dt.Second != 0 || dt.Minute != 0 || dt.Hour != 0 || dt.Day != 1 || (dt.Month - 1)% increment != 0) { dtNew = dtNew.AddMilliseconds(-dt.Millisecond); dtNew = dtNew.AddSeconds(-dt.Second); dtNew = dtNew.AddMinutes(-dt.Minute); dtNew = dtNew.AddHours(-dt.Hour); dtNew = dtNew.AddDays(-dt.Day + 1); dtNew = dtNew.AddMonths(-((dt.Month - 1) % increment)); if (isCeiling) dtNew = dtNew.AddMonths(increment); } break; case DateTimeInterval.Year: if (dt.Millisecond != 0 || dt.Second != 0 || dt.Minute != 0 || dt.Hour != 0 || dt.Day != 1 || dt.Month != 1 || dt.Year % increment != 0) { dtNew = dtNew.AddMilliseconds(-dt.Millisecond); dtNew = dtNew.AddSeconds(-dt.Second); dtNew = dtNew.AddMinutes(-dt.Minute); dtNew = dtNew.AddHours(-dt.Hour); dtNew = dtNew.AddDays(-dt.Day + 1); dtNew = dtNew.AddMonths(-dt.Month + 1); dtNew = dtNew.AddYears(-(dt.Year % increment)); if (isCeiling) dtNew = dtNew.AddYears(increment); } break; } return dtNew; }
DateTime DateTimeCeiling(DateTime dt, DateTimeInterval interval, int increment) { return DateTimeFloorCeiling(dt, interval, increment, true); }
DateTime AddIncrement(DateTime dt, DateTimeInterval interval, int increment) { DateTime dtNew = dt.AddSeconds(1); return DateTimeCeiling(dt.AddMilliseconds(500), interval, increment); }
protected override void CalculateAxisItems(Type propertyType, ref double minValue, ref double maxValue) { if (propertyType != typeof(DateTime)) throw new NotImplementedException("AdaptableDateTimeAxis is only for a DateTime axis."); TestIncrementCollection(SecondIncrements, "Year"); TestIncrementCollection(MinuteIncrements, "Minute"); TestIncrementCollection(HourIncrements, "Hour"); TestIncrementCollection(DayIncrements, "Day"); TestIncrementCollection(MonthIncrements, "Month"); TestIncrementCollection(YearIncrements, "Year"); if (MaximumItems < 2) throw new ArgumentException("MaximumItems must be at least 2"); if (minValue == maxValue) { minValue -= ConvertToDouble(TimeSpan.FromSeconds(1)); maxValue += ConvertToDouble(TimeSpan.FromSeconds(1)); } DateTime minDateTime = (DateTime)ConvertFromDouble(minValue, propertyType); DateTime maxDateTime = (DateTime)ConvertFromDouble(maxValue, propertyType); Int32Collection[] incrementsArray = { SecondIncrements, MinuteIncrements, HourIncrements, DayIncrements, MonthIncrements, YearIncrements }; int incrementsIndex = 0; int incrementMultiplier = 1; DateTimeInterval interval = DateTimeInterval.Second; while (true) { Int32Collection increments = incrementsArray[(int)interval]; int increment = incrementMultiplier * increments[incrementsIndex]; DateTime minAxisDateTime = DateTimeFloor(minDateTime, interval, increment); DateTime maxAxisDateTime = DateTimeCeiling(maxDateTime, interval, increment); DateTime dtTick = minAxisDateTime; int count = 1; while (true) { dtTick = AddIncrement(dtTick, interval, increment); count++; if (dtTick >= maxAxisDateTime) break; if (count > MaximumItems) break; } if (count <= MaximumItems) { minValue = ConvertToDouble(minAxisDateTime); maxValue = ConvertToDouble(maxAxisDateTime); dtTick = minAxisDateTime; for (int i = 0; i < count; i++) { AxisItem axisItem = new AxisItem() { Item = dtTick, Offset = Length * (ConvertToDouble(dtTick) - minValue) / (maxValue - minValue) }; AxisItems.Add(axisItem); dtTick = AddIncrement(dtTick, interval, increment); } DateTimeInterval = interval; break; } if (incrementsIndex < increments.Count - 1) { incrementsIndex++; } else { incrementsIndex = 0; if (interval != DateTimeInterval.Year) interval++; else incrementMultiplier *= 10; } } }
public static DataTable SampleDataByInterval(DataView sourceView, string[] columns, string samplingField, int intervalValue, DateTimeInterval intervalType) { DataTable newTable = new DataTable(); for (int i = 0; i < columns.Length; i++) newTable.Columns.Add(new DataColumn(columns[i], sourceView.Table.Columns[columns[i]].DataType)); DateTime lastValue; if (sourceView.Count > 0) { //Add the first row lastValue = (DateTime)sourceView[0][samplingField]; DataRow newRow = newTable.NewRow(); for (int i = 0; i < columns.Length; i++) newRow[columns[i]] = sourceView[0][columns[i]]; newTable.Rows.Add(newRow); //Add all rows for (int i = 1; i < sourceView.Count; i++) { DataRow dr = sourceView[i].Row; DateTime currentValue = (DateTime)dr[samplingField]; int currentInterval; if (intervalType == DateTimeInterval.Months) currentInterval = DateTimeHelper.MonthsDifference(currentValue, lastValue); else throw new ApplicationException("Interval not supported"); if (currentInterval >= intervalValue || (i + 1) == sourceView.Count) { if (intervalType == DateTimeInterval.Months) lastValue = lastValue.AddMonths(intervalValue); else throw new ApplicationException("Interval not supported"); newRow = newTable.NewRow(); for (int j = 0; j < columns.Length; j++) newRow[columns[j]] = dr[columns[j]]; newTable.Rows.Add(newRow); } } } return newTable; }