public static DateTime DateAdd(DateInterval Interval, double Number, DateTime DateValue)
        {
            int years = (int) Math.Round(Conversion.Fix(Number));
            switch (Interval)
            {
                case DateInterval.Year:
                    return CurrentCalendar.AddYears(DateValue, years);

                case DateInterval.Quarter:
                    return DateValue.AddMonths(years * 3);

                case DateInterval.Month:
                    return CurrentCalendar.AddMonths(DateValue, years);

                case DateInterval.DayOfYear:
                case DateInterval.Day:
                case DateInterval.Weekday:
                    return DateValue.AddDays((double) years);

                case DateInterval.WeekOfYear:
                    return DateValue.AddDays(years * 7.0);

                case DateInterval.Hour:
                    return DateValue.AddHours((double) years);

                case DateInterval.Minute:
                    return DateValue.AddMinutes((double) years);

                case DateInterval.Second:
                    return DateValue.AddSeconds((double) years);
            }
            throw new ArgumentException(Utils.GetResourceString("Argument_InvalidValue1", new string[] { "Interval" }));
        }
        public void AccountForEfficiencies_FixedEnd_MultipleDateIntervalEfficiencies_ReturnsCorrectAnswer()
        {
            //         +------------+
            //       |0|  |0|  |0|

            // Result:
            //   +------------------+
            //       |0|  |0|  |0|

            // Arrange
            var now = DateTime.Now;
            var dateInterval = new DateInterval(now, now.AddDays(5));

            var dateIntervalEfficiencies = new List<DateIntervalEfficiency>();
            var efficiency1 = new DateIntervalEfficiency(now.AddDays(1), now.AddDays(2), 0);
            var efficiency2 = new DateIntervalEfficiency(now.AddDays(3), now.AddDays(4), 0);
            var efficiency3 = new DateIntervalEfficiency(now.AddDays(5), now.AddDays(6), 0);

            dateIntervalEfficiencies.Add(efficiency1);
            dateIntervalEfficiencies.Add(efficiency2);
            dateIntervalEfficiencies.Add(efficiency3);

            // Act
            var newDateInterval = dateInterval.AccountForEfficiencies(dateIntervalEfficiencies, FixedEndPoint.Max);

            var correctDateInterval = new DateInterval(dateInterval.Max.Value.Add(-dateInterval.Duration).Add(-efficiency1.Duration).Add(-efficiency2.Duration).Add(-efficiency3.Duration), dateInterval.Max.Value);

            // Assert
            Assert.AreEqual(correctDateInterval, newDateInterval);
        }
示例#3
1
        public void CompareTo_DateIntervalWithSameStartAndSameEndDates_ReturnsZero()
        {
            // Arrange
            var dateInterval1 = new DateInterval(now, inOneHour);
            var dateInterval2 = new DateInterval(now, inOneHour);

            // Act
            int compareToValue = dateInterval1.CompareTo(dateInterval2); // Shortest duration comes first

            // Assert
            Assert.True(compareToValue == 0);
        }
示例#4
0
        public static DateTime DateAdd(DateInterval interval, int value, DateTime date)
        {
            int ms = date.GetTime();
            DateTime result;
            switch (interval)
            {
                case DateInterval.Milliseconds:
                    result = new DateTime(ms + value);
                    break;
                case DateInterval.Seconds:
                    result = new DateTime(ms + (value * 1000));
                    break;
                case DateInterval.Minutes:
                    result = new DateTime(ms + (value * 1000 * 60));
                    break;
                case DateInterval.Hours:
                    result = new DateTime(ms + (value * 1000 * 60 * 60));
                    break;
                case DateInterval.Days:
                    result = new DateTime(ms + (value * 1000 * 60 * 60 * 24));
                    break;
                default:
                    result = date;
                    break;
            }

            return result;
        }
 public DateTimeSearchModel(string title, string columnName, DateInterval interval = DateInterval.Month)
 {
     this.title = title;
       ColumnName = columnName;
       endDate = DateTime.Now;
       switch (interval)
       {
     case DateInterval.Day:
       startDate = DateTime.Now.AddDays(-1);
       break;
     case DateInterval.Week:
       startDate = DateTime.Now.AddDays(-7);
       break;
     case DateInterval.Month:
       startDate = DateTime.Now.AddMonths(-1);
       break;
     case DateInterval.Quarter:
       startDate = DateTime.Now.AddMonths(-3);
       break;
     case DateInterval.Year:
       startDate = DateTime.Now.AddYears(-1);
       break;
       }
       originalDate = startDate;
 }
示例#6
0
 /// <summary>
 /// Devuelve un valor Long que especifica el número de
 /// intervalos de tiempo entre dos valores Date.
 /// </summary>
 /// <param name="interval">Obligatorio. Valor de enumeración
 /// DateInterval o expresión String que representa el intervalo
 /// de tiempo que se desea utilizar como unidad de diferencia
 /// entre Date1 y Date2.</param>
 /// <param name="date1">Obligatorio. Date. Primer valor de
 /// fecha u hora que se desea utilizar en el cálculo.</param>
 /// <param name="date2">Obligatorio. Date. Segundo valor de
 /// fecha u hora que se desea utilizar en el cálculo.</param>
 /// <returns></returns>
 public static long DateDiff(DateInterval interval, DateTime date1, DateTime date2)
 {
     long rs = 0;
     TimeSpan diff = date2.Subtract(date1);
     switch (interval)
     {
         case DateInterval.Day:
         case DateInterval.DayOfYear:
             rs = (long)diff.TotalDays;
             break;
         case DateInterval.Hour:
             rs = (long)diff.TotalHours;
             break;
         case DateInterval.Minute:
             rs = (long)diff.TotalMinutes;
             break;
         case DateInterval.Month:
             rs = (date2.Month - date1.Month) + (12*DateTimeExtension.DateDiff(DateInterval.Year, date1, date2));
             break;
         case DateInterval.Quarter:
             rs = (long)Math.Ceiling((double)(DateTimeExtension.DateDiff(DateInterval.Month, date1, date2) / 3.0));
             break;
         case DateInterval.Second:
             rs = (long)diff.TotalSeconds;
             break;
         case DateInterval.Weekday:
         case DateInterval.WeekOfYear:
             rs = (long)(diff.TotalDays/7);
             break;
         case DateInterval.Year:
             rs = date2.Year - date1.Year;
             break;
     }//switch
     return rs;
 }
示例#7
0
        /// <summary>
        /// Gets the difference between two dates based on an interval.
        /// </summary>
        /// <param name="interval">The interval to use (seconds, minutes, hours, days, months, years)</param>
        /// <param name="date1">The date to use for comparison.</param>
        /// <param name="date2">The date to compare against the first date.</param>
        /// <returns></returns>
        public static object GetDateDiff(DateInterval interval, DateTime date1, DateTime date2)
        {
            object returnValue = null;
            TimeSpan t;

            object diff = 0.0;

            //returns negative value if date1 is more recent
            t = date2 - date1;

            switch (interval)
            {
                case DateInterval.Second:
                    diff = t.TotalSeconds;
                    break;
                case DateInterval.Minute:
                    diff = t.TotalMinutes;
                    break;
                case DateInterval.Hour:
                    diff = t.TotalHours;
                    break;
                case DateInterval.Day:
                    diff = t.TotalDays;
                    break;
                case DateInterval.Month:
                    diff = t.TotalDays / 365.25 * 12.0;
                    break;
                case DateInterval.Year:
                    diff = t.TotalDays / 365.25;
                    break;
            }

            returnValue = Convert.ToInt32(diff);
            return returnValue;
        }
 public void Length_Exclusive()
 {
     LocalDate start = new LocalDate(2000, 1, 1);
     LocalDate end = new LocalDate(2000, 2, 10);
     var interval = new DateInterval(start, end, false);
     Assert.AreEqual(40, interval.Length);
 }
示例#9
0
 internal static long DateDiff(DateInterval Interval, System.DateTime StartDate, System.DateTime EndDate)
 {
     long lngDateDiffValue = 0;
     System.TimeSpan TS = new System.TimeSpan(EndDate.Ticks - StartDate.Ticks);
     switch (Interval)
     {
         case DateInterval.Day:
             lngDateDiffValue = (long)TS.Days;
             break;
         case DateInterval.Hour:
             lngDateDiffValue = (long)TS.TotalHours;
             break;
         case DateInterval.Minute:
             lngDateDiffValue = (long)TS.TotalMinutes;
             break;
         case DateInterval.Month:
             lngDateDiffValue = (long)(TS.Days / 30);
             break;
         case DateInterval.Quarter:
             lngDateDiffValue = (long)((TS.Days / 30) / 3);
             break;
         case DateInterval.Second:
             lngDateDiffValue = (long)TS.TotalSeconds;
             break;
         case DateInterval.Week:
             lngDateDiffValue = (long)(TS.Days / 7);
             break;
         case DateInterval.Year:
             lngDateDiffValue = (long)(TS.Days / 365);
             break;
     }
     return (lngDateDiffValue);
 }
示例#10
0
 public void Construction_DefaultToInclusive()
 {
     LocalDate start = new LocalDate(2000, 1, 1);
     LocalDate end = new LocalDate(2001, 6, 19);
     var interval = new DateInterval(start, end);
     Assert.IsTrue(interval.Inclusive);
 }
示例#11
0
 public static long DateDiff(this DateTime startDate, DateTime endDate, DateInterval interval = DateInterval.Day)
 {
     long lngDateDiffValue = 0;
       var timeSpan = new TimeSpan(endDate.Ticks - startDate.Ticks);
       switch (interval)
       {
     case DateInterval.Second:
       lngDateDiffValue = (long) timeSpan.TotalSeconds;
       break;
     case DateInterval.Minute:
       lngDateDiffValue = (long) timeSpan.TotalMinutes;
       break;
     case DateInterval.Hour:
       lngDateDiffValue = (long) timeSpan.TotalHours;
       break;
     case DateInterval.Day:
       lngDateDiffValue = timeSpan.Days;
       break;
     case DateInterval.Week:
       lngDateDiffValue = timeSpan.Days/7;
       break;
     case DateInterval.Month:
       lngDateDiffValue = timeSpan.Days/30;
       break;
     case DateInterval.Quarter:
       lngDateDiffValue = (timeSpan.Days/30)/3;
       break;
     case DateInterval.Year:
       lngDateDiffValue = timeSpan.Days/365;
       break;
       }
       return (lngDateDiffValue);
 }
示例#12
0
        public static IList<ITask> Collapse(this IEnumerable<ITask> taskCollection)
        {
            var taskList = taskCollection.ToList();

            if (taskCollection == null)
            {
                return null;
            }

            var output = new Collection<ITask>();

            // Grabbing all time split points and sorting them
            List<DateTime> timeEvents = taskList.SelectMany(task => new[] { task.StartTime, task.EndTime })
                                                     .Distinct()
                                                     .OrderBy(x => x)
                                                     .ToList();

            for (var i = 0; i < timeEvents.Count - 1; i++)
            {
                var newSpan = new DateInterval(timeEvents[i], timeEvents[i + 1]);

                var overlappingTasks = taskList.Where(x => x.DateInterval.Overlaps(newSpan));

                if (overlappingTasks.Any())
                {
                    var quantityPerHour = overlappingTasks.Sum(x => x.QuantityPerHour);
                    output.Add(Task.CreateUsingQuantityPerHour(newSpan, quantityPerHour));
                }
            }

            return output;
        }
示例#13
0
 public void Construction_Properties()
 {
     LocalDate start = new LocalDate(2000, 1, 1);
     LocalDate end = new LocalDate(2001, 6, 19);
     var interval = new DateInterval(start, end, false);
     Assert.AreEqual(start, interval.Start);
     Assert.AreEqual(end, interval.End);
     Assert.IsFalse(interval.Inclusive);
 }
        public void FixedStartPointNoOverlapsWithOffset(IAccountForEfficiencies accountForEfficienciesCalculator)
        {
            // 1% efficiency
            var dateIntervalEfficiencies = DateIntervalCollectionGenerator.NoOverlaps(this.now, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1), this.numberOfIntervals)
                .Select(interval => new DateIntervalEfficiency(interval, 1)).ToList();

            var initialInterval = new DateInterval(this.now, dateIntervalEfficiencies.Last().Max.Value);

            accountForEfficienciesCalculator.AccountForEfficiencies(initialInterval, dateIntervalEfficiencies, FixedEndPoint.Min);
        }
        public void Setup()
        {
            now = DateTime.Now;

            nowAndTenDaysInterval = new DateInterval(now, now.AddDays(10));
            nowAndFiveDaysInterval = new DateInterval(now, now.AddDays(5));
            twoDaysAndFiveDaysInterval = new DateInterval(now.AddDays(2), now.AddDays(5));
            threeDaysAgoAndTwelveDaysInterval = new DateInterval(now.AddDays(-3), now.AddDays(12));
            thirteenDaysAndFourteenDaysInterval = new DateInterval(now.AddDays(13), now.AddDays(14));
        }
        public void FixedStartPointNoOverlapsWithOffsetWithSpan(double spanEfficiency, int spanPriority, bool assertIntervalsEquality)
        {
            // 1% efficiency
            var dateIntervalEfficiencies = DateIntervalCollectionGenerator.NoOverlaps(now, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1), numberOfIntervals)
                .Select(interval => new DateIntervalEfficiency(interval, 1)).ToList();

            var initialInterval = new DateInterval(now, dateIntervalEfficiencies.Last().Max.Value);

            dateIntervalEfficiencies.Add(new DateIntervalEfficiency(initialInterval, spanEfficiency, spanPriority));

            RunAccountForEfficienciesBenchmarkTest(initialInterval, dateIntervalEfficiencies, FixedEndPoint.Min, assertIntervalsEquality);
        }
示例#17
0
 public void Equals_EqualValues()
 {
     LocalDate start = new LocalDate(2000, 1, 1);
     LocalDate end = new LocalDate(2001, 6, 19);
     var interval1 = new DateInterval(start, end, false);
     var interval2 = new DateInterval(start, end, false);
     Assert.AreEqual(interval1, interval2);
     Assert.AreEqual(interval1.GetHashCode(), interval2.GetHashCode());
     Assert.IsTrue(interval1 == interval2);
     Assert.IsFalse(interval1 != interval2);
     Assert.IsTrue(interval1.Equals(interval2)); // IEquatable implementation
 }
示例#18
0
        public void CompareTo_DateIntervalWithSameStartAndDifferentEndDates_ReturnsShortestDurationFirstReversed()
        {
            // Arrange
            var dateInterval1 = new DateInterval(now, inThreeHours);
            var dateInterval2 = new DateInterval(now, inOneHour);

            // Act
            int compareToValue = dateInterval1.CompareTo(dateInterval2); // Shortest duration comes first

            // Assert
            Assert.True(compareToValue == 1);
        }
示例#19
0
        public void CompareTo_DateIntervalWithDifferentStartAndDifferentEndDates_ReturnsEarliestStart()
        {
            // Arrange
            var dateInterval1 = new DateInterval(now, inOneHour);
            var dateInterval2 = new DateInterval(inOneHour, inThreeHours);

            // Act
            int compareToValue = dateInterval1.CompareTo(dateInterval2);

            // Assert
            Assert.True(compareToValue == -1);
        }
示例#20
0
        public static IEnumerable<DateInterval> GetDateIntervalsAllDescendingEndTimes(int count)
        {
            var date = DateTime.Now;
            var DateIntervals = new DateInterval[count];

            for (int i = 0; i < count; i++)
            {
                DateIntervals[count - i - 1] = new DateInterval(date.AddMinutes(-i), date.AddMinutes(i));
            }

            return new List<DateInterval>(DateIntervals).OrderBy( x => x );
        }
示例#21
0
文件: Program.cs 项目: Orcomp/Orcomp
        private static List<DateInterval> CreatetestCase(Random rand, DateTime start, int MaxNumberOfDateRanges)
        {
            var orderedDateRanges = new List<DateInterval>();

            for (int i = rand.Next(MaxNumberOfDateRanges)+10; i != 0; --i)
            {
                var DRStart = start.AddMinutes(rand.Next(1000));
                var DR = new DateInterval(DRStart, DRStart.AddMinutes(rand.Next(1000)));
                orderedDateRanges.Add(DR);
            }
            orderedDateRanges.Sort();
            return orderedDateRanges;
        }
示例#22
0
        public void AccountForEfficiencies_FixedEnd_EmptyListOfDateIntervalEfficiencies_ReturnsUnchangedDateInterval()
        {
            // Arrange
            var now = DateTime.Now;
            var dateInterval = new DateInterval(now, now.AddDays(1));

            var dateIntervalEfficiencies = new List<DateIntervalEfficiency>();

            // Act
            var newDateInterval = dateInterval.AccountForEfficiencies(dateIntervalEfficiencies, FixedEndPoint.Max);

            // Assert
            Assert.AreEqual(dateInterval, newDateInterval);
        }
示例#23
0
        public static long DateDiff(DateInterval interval, DateTime dt1, DateTime dt2, DayOfWeek eFirstDayOfWeek)
        {
            if (interval == DateInterval.Year)
                return dt2.Year - dt1.Year;

            if (interval == DateInterval.Month)
                return (dt2.Month - dt1.Month) + (12 * (dt2.Year - dt1.Year));

            TimeSpan ts = dt2 - dt1;

            if (interval == DateInterval.Day || interval == DateInterval.DayOfYear)
                return Round(ts.TotalDays);

            if (interval == DateInterval.Hour)
                return Round(ts.TotalHours);

            if (interval == DateInterval.Minute)
                return Round(ts.TotalMinutes);

            if (interval == DateInterval.Second)
                return Round(ts.TotalSeconds);

            if (interval == DateInterval.Weekday)
            {
                return Round(ts.TotalDays / 7.0);
            }

            if (interval == DateInterval.WeekOfYear)
            {
                while (dt2.DayOfWeek != eFirstDayOfWeek)
                    dt2 = dt2.AddDays(-1);
                while (dt1.DayOfWeek != eFirstDayOfWeek)
                    dt1 = dt1.AddDays(-1);
                ts = dt2 - dt1;
                return Round(ts.TotalDays / 7.0);
            }

            if (interval == DateInterval.Quarter)
            {
                double d1Quarter = GetQuarter(dt1.Month);
                double d2Quarter = GetQuarter(dt2.Month);
                double d1 = d2Quarter - d1Quarter;
                double d2 = (4 * (dt2.Year - dt1.Year));
                return Round(d1 + d2);
            }

            return 0;
        }
示例#24
0
 public void Equals_DifferentCalendars()
 {
     LocalDate start1 = new LocalDate(2000, 1, 1);
     LocalDate end1 = new LocalDate(2001, 6, 19);
     // This is a really, really similar calendar to ISO, but we do distinguish.
     // TODO: Should we?
     LocalDate start2 = start1.WithCalendar(CalendarSystem.Gregorian);
     LocalDate end2 = end1.WithCalendar(CalendarSystem.Gregorian);
     var interval1 = new DateInterval(start1, end1, false);
     var interval2 = new DateInterval(start2, end2, false);
     Assert.AreNotEqual(interval1, interval2);
     Assert.AreNotEqual(interval1.GetHashCode(), interval2.GetHashCode());
     Assert.IsFalse(interval1 == interval2);
     Assert.IsTrue(interval1 != interval2);
     Assert.IsFalse(interval1.Equals(interval2)); // IEquatable implementation
 }
示例#25
0
 public void Equals_DifferentCalendars()
 {
     LocalDate start1 = new LocalDate(2000, 1, 1);
     LocalDate end1 = new LocalDate(2001, 6, 19);
     // This is a really, really similar calendar to ISO - the dates could differ by week of year,
     // but that's all.
     LocalDate start2 = start1.WithCalendar(CalendarSystem.GetGregorianCalendar(1));
     LocalDate end2 = end1.WithCalendar(CalendarSystem.GetGregorianCalendar(1));
     var interval1 = new DateInterval(start1, end1, false);
     var interval2 = new DateInterval(start2, end2, false);
     Assert.AreNotEqual(interval1, interval2);
     Assert.AreNotEqual(interval1.GetHashCode(), interval2.GetHashCode());
     Assert.IsFalse(interval1 == interval2);
     Assert.IsTrue(interval1 != interval2);
     Assert.IsFalse(interval1.Equals(interval2)); // IEquatable implementation
 }
        public void FixedStartPointWithOverlaps()
        {
            // With decreasing efficiency
            // |-------------------|  90
            //   |---------------|    80
            //      |---------|       70
            //        |-----|         60

            // 1% efficiency
            var dateIntervalEfficiencies = DateIntervalCollectionGenerator.OverlapsWithDecreasingDuration(now, TimeSpan.FromMinutes(1), numberOfIntervals)
                .Select((interval, i) => new DateIntervalEfficiency(interval, numberOfIntervals - i)).ToList();

            var initialInterval = new DateInterval(now, dateIntervalEfficiencies.First().Max.Value);

            RunAccountForEfficienciesBenchmarkTest(initialInterval, dateIntervalEfficiencies, FixedEndPoint.Min, assertIntervalsEquality: false);
        }
示例#27
0
        public static long DateDiff(this DateTime first, DateTime second, DayOfWeek firstDayOfWeek, DateInterval interval)
        {
            if (interval == DateInterval.Year)
                return second.Year - first.Year;

            if (interval == DateInterval.Month)
                return (second.Month - first.Month) + (12 * (second.Year - first.Year));

            TimeSpan ts = second - first;

            if (interval == DateInterval.Day || interval == DateInterval.DayOfYear)
                return Round(ts.TotalDays);

            if (interval == DateInterval.Hour)
                return Round(ts.TotalHours);

            if (interval == DateInterval.Minute)
                return Round(ts.TotalMinutes);

            if (interval == DateInterval.Second)
                return Round(ts.TotalSeconds);

            if (interval == DateInterval.Weekday)
            {
                return Round(ts.TotalDays / 7.0);
            }

            if (interval == DateInterval.WeekOfYear)
            {
                while (second.DayOfWeek != firstDayOfWeek)
                    second = second.AddDays(-1);
                while (first.DayOfWeek != firstDayOfWeek)
                    first = first.AddDays(-1);
                ts = second - first;
                return Round(ts.TotalDays / 7.0);
            }

            if (interval == DateInterval.Quarter)
            {
                double d1Quarter = GetQuarter(first);
                double d2Quarter = GetQuarter(second);
                double d1 = d2Quarter - d1Quarter;
                double d2 = (4 * (second.Year - first.Year));
                return Round(d1 + d2);
            }
            return 0;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="DateRangeBound"/> class.
 /// </summary>
 /// <param name="relativeAmount">The relative amount.</param>
 /// <param name="relativeInterval">The relative interval.</param>
 /// <param name="specificDate">The specific date.</param>
 /// <param name="windowAmount">The window amount.</param>
 /// <param name="windowInterval">The window interval.</param>
 public DateRangeBound(int? relativeAmount, DateInterval? relativeInterval, DateTime? specificDate, int? windowAmount, DateInterval? windowInterval)
 {
     if (specificDate.HasValue)
     {
         this.SpecificDate = specificDate;
     }
     else if (windowAmount.HasValue && windowInterval.HasValue)
     {
         this.WindowAmount = windowAmount;
         this.WindowInterval = windowInterval;
     }
     else
     {
         this.RelativeAmount = relativeAmount;
         this.RelativeInterval = relativeInterval;
     }
 }
示例#29
0
	public static long DateDiff(DateInterval intervalType, System.DateTime dateOne, System.DateTime dateTwo)
	{
		switch (intervalType)
		{
			case DateInterval.Day:
			case DateInterval.DayOfYear:
				System.TimeSpan spanForDays = dateTwo - dateOne;
				return (long)spanForDays.TotalDays;
			case DateInterval.Hour:
				System.TimeSpan spanForHours = dateTwo - dateOne;
				return (long)spanForHours.TotalHours;
			case DateInterval.Minute:
				System.TimeSpan spanForMinutes = dateTwo - dateOne;
				return (long)spanForMinutes.TotalMinutes;
			case DateInterval.Month:
				return ((dateTwo.Year - dateOne.Year) * 12) + (dateTwo.Month - dateOne.Month);
			case DateInterval.Quarter:
				long dateOneQuarter = (long)System.Math.Ceiling(dateOne.Month / 3.0);
				long dateTwoQuarter = (long)System.Math.Ceiling(dateTwo.Month / 3.0);
				return (4 * (dateTwo.Year - dateOne.Year)) + dateTwoQuarter - dateOneQuarter;
			case DateInterval.Second:
				System.TimeSpan spanForSeconds = dateTwo - dateOne;
				return (long)spanForSeconds.TotalSeconds;
			case DateInterval.Weekday:
				System.TimeSpan spanForWeekdays = dateTwo - dateOne;
				return (long)(spanForWeekdays.TotalDays / 7.0);
			case DateInterval.WeekOfYear:
				System.DateTime dateOneModified = dateOne;
				System.DateTime dateTwoModified = dateTwo;
				while (dateTwoModified.DayOfWeek != System.Globalization.DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek)
				{
					dateTwoModified = dateTwoModified.AddDays(-1);
				}
				while (dateOneModified.DayOfWeek != System.Globalization.DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek)
				{
					dateOneModified = dateOneModified.AddDays(-1);
				}
				System.TimeSpan spanForWeekOfYear = dateTwoModified - dateOneModified;
				return (long)(spanForWeekOfYear.TotalDays / 7.0);
			case DateInterval.Year:
				return dateTwo.Year - dateOne.Year;
			default:
				return 0;
		}
	}
示例#30
0
        /// <summary>
        /// Gets the scalar difference between two dates given a <see cref="DateInterval"/> value.
        /// </summary>
        /// <param name="interval">The interval to calculate</param>
        /// <param name="start">The start date</param>
        /// <param name="end">The end date</param>
        /// <param name="excludeEndDate">If true, the difference is exclusive of the end date</param>
        /// <returns></returns>
        public static int GetDifference(DateInterval interval, DateTime start, DateTime end, bool excludeEndDate = false)
        {
            var sum = 0;
            var span = new DateSpan(start, end);

            switch (interval)
            {
                case DateInterval.Years:
                    sum += span.Years;
                    break;
                case DateInterval.Months:
                    if (span.Years > 0)
                    {
                        sum += span.Years * 12;
                    }
                    sum += span.Months;
                    sum += span.Weeks / 4; // Helps resolve lower resolution
                    break;
                case DateInterval.Weeks:
                    sum = GetDifferenceInDays(start, span, excludeEndDate) / 7;
                    break;
                case DateInterval.Days:
                    sum = GetDifferenceInDays(start, span, excludeEndDate);
                    break;
                case DateInterval.Hours:
                    sum = GetDifferenceInDays(start, span, excludeEndDate) * 24;
                    sum += span.Hours;
                    break;
                case DateInterval.Minutes:
                    sum = GetDifferenceInDays(start, span, excludeEndDate) * 24 * 60;
                    sum += span.Hours * 60;
                    sum += span.Minutes;
                    break;
                case DateInterval.Seconds:
                    sum = GetDifferenceInDays(start, span, excludeEndDate) * 24 * 60 * 60;
                    sum += span.Hours * 60 * 60;
                    sum += span.Minutes * 60;
                    sum += span.Seconds;
                    break;
                default:
                    throw new ArgumentOutOfRangeException("interval");
            }

            return sum;
        }
示例#31
0
        }         // constructor

        public void Run()
        {
            FileCache.ErrorMsg = string.Empty;

            for (int i = 0; i < FileList.Count; i++)
            {
                HttpPostedFileBase oFile = FileList[i];

                if (oFile == null)
                {
                    ms_oLog.Debug("File {0}: not found, ignoring.", i);
                    continue;
                }                 // if

                ms_oLog.Debug("File {0}, name: {1}", i, oFile.FileName);

                if (oFile.ContentLength == 0)
                {
                    ms_oLog.Debug("File {0}: is empty, ignoring.", i);
                    continue;
                }                 // if

                var oFileContents = new byte[oFile.ContentLength];

                int nRead = oFile.InputStream.Read(oFileContents, 0, oFile.ContentLength);

                if (nRead != oFile.ContentLength)
                {
                    ms_oLog.Warn("File {0}: failed to read entire file contents, ignoring.", i);
                    continue;
                }                 // if

                string sMimeType = m_oLimitations.DetectFileMimeType(oFileContents, oFile.FileName, oLog: ms_oLog);

                ms_oLog.Debug("File {0}, name: {1}, MIME type {2}", i, oFile.FileName, sMimeType);

                if (string.IsNullOrWhiteSpace(sMimeType))
                {
                    ms_oLog.Debug("File {0}: has unsupported content type, ignoring.", i);
                    continue;
                }                 // if

                SaveToDisc(CustomerID, OneUploadLimitation.FixFileName(oFile.FileName), oFileContents);

                var smd = new SheafMetaData {
                    BaseFileName = OneUploadLimitation.FixFileName(oFile.FileName),
                    DataType     = DataType.VatReturn,
                    FileType     = FileType.Pdf,
                    Thrasher     = null
                };

                FileCache.Add(smd, oFileContents);

                var    vrpt = new VatReturnPdfThrasher(false, ms_oLog);
                ISeeds oResult;

                try {
                    oResult = vrpt.Run(smd, oFileContents);
                }
                catch (Exception e) {
                    ms_oLog.Warn(e, "Failed to parse file {0} named {1}:", i, oFile.FileName);
                    continue;
                }                 // try

                if (oResult == null)
                {
                    ErrorMsg = m_sErrorMsg + " " + ((VatReturnSeeds)vrpt.Seeds).FatalError;
                    continue;
                }                 // if

                var oSeeds = (VatReturnSeeds)oResult;

                var di = new DateInterval(oSeeds.DateFrom, oSeeds.DateTo);

                ms_oLog.Debug("HMRC file cache state before adding file {0}: {1}.", oFile.FileName, FileCache);

                if (FileCache.Intersects(oSeeds.RegistrationNo, di))
                {
                    return;
                }

                FileCache.Add(oSeeds.RegistrationNo, di, smd, oResult);

                ms_oLog.Debug("HMRC file cache state after adding file {0}: {1}.", oFile.FileName, FileCache);
            }     // for
        }         // Run
示例#32
0
 protected override LocalDate GetProperty2Value(DateInterval value) => value.End;
示例#33
0
 public static bool Starts(this DateInterval x, DateInterval y) => x.Start == y.Start && x.End < y.End;
示例#34
0
        public static ReportDataSource HodnotaSmluvPerZverejneni(string query, DateInterval interval)
        {
            DateTime minDate = new DateTime(2012, 1, 1);
            DateTime maxDate = DateTime.Now.Date.AddDays(1);

            string datumFormat = "MMM yyyy";

            switch (interval)
            {
            case DateInterval.Day:
                datumFormat = "dd.MM.yy";
                break;

            case DateInterval.Week:
                datumFormat = "dd.MM.yy";
                break;

            case DateInterval.Month:
                datumFormat = "MMM yyyy";
                break;

            case DateInterval.Quarter:
                datumFormat = "MMM yyyy";
                break;

            case DateInterval.Year:
                datumFormat = "yyyy";
                break;

            default:
                break;
            }

            AggregationContainerDescriptor <HlidacStatu.Lib.Data.Smlouva> aggs = new AggregationContainerDescriptor <HlidacStatu.Lib.Data.Smlouva>()
                                                                                 .DateHistogram("x-agg", h => h
                                                                                                .Field(f => f.datumUzavreni)
                                                                                                .Interval(interval)
                                                                                                .Format("yyyy-MM-dd")
                                                                                                .Aggregations(agg => agg
                                                                                                              .Sum("sumincome", s => s
                                                                                                                   .Field(ff => ff.CalculatedPriceWithVATinCZK)
                                                                                                                   )
                                                                                                              )
                                                                                                );
            ReportDataSource rdsPerIntervalSumPrice = new ReportDataSource(new ReportDataSource.Column[]
            {
                new ReportDataSource.Column()
                {
                    Name       = "Měsíc",
                    TextRender = (s) => {
                        DateTime dt = ((DateTime)s);
                        return(string.Format("Date.UTC({0}, {1}, {2})", dt.Year, dt.Month - 1, dt.Day));
                    }
                },
                new ReportDataSource.Column()
                {
                    Name = "Součet cen", HtmlRender = (s) => { return(HlidacStatu.Lib.Data.Smlouva.NicePrice((double?)s, html: true, shortFormat: true)); }
                },
            });

            var res = HlidacStatu.Lib.Data.Smlouva.Search.SimpleSearch("( " + query + " ) AND datumUzavreni:{" + HlidacStatu.Util.RenderData.ToElasticDate(minDate) + " TO " + HlidacStatu.Util.RenderData.ToElasticDate(maxDate) + "}", 1, 0, HlidacStatu.Lib.Data.Smlouva.Search.OrderResult.FastestForScroll, anyAggregation: aggs, exactNumOfResults: true);

            foreach (Nest.DateHistogramBucket val in
                     ((BucketAggregate)res.Result.Aggregations["x-agg"]).Items
                     )
            {
                if (val.Date >= minDate && val.Date <= maxDate)
                {
                    rdsPerIntervalSumPrice.AddRow(
                        new DateTime(val.Date.Ticks, DateTimeKind.Utc).ToLocalTime(),
                        ((Nest.DateHistogramBucket)val).Sum("sumincome").Value
                        );
                }
            }


            return(rdsPerIntervalSumPrice);
        }
示例#35
0
 public static ReportDataSource HodnotaSmluvPerZverejneni(DateInterval interval)
 {
     return(HodnotaSmluvPerZverejneni("-id:pre* ", interval));
 }
示例#36
0
        /// <summary>
        /// Works like Visual Basic DateDiff method.
        /// </summary>
        /// <param name="interval"></param>
        /// <param name="date1"></param>
        /// <param name="date2"></param>
        /// <returns></returns>
        public static long DateDiff(DateInterval interval, DateTime date1, DateTime date2)
        {
            long     _value = 0;
            TimeSpan _span  = date2 - date1;

            switch (interval)
            {
            case DateInterval.Day:
            case DateInterval.DayOfYear:
                _value = _span.Days; break;

            case DateInterval.Hour:
                if (_span.Hours > 0)
                {
                    _value = _span.Hours;
                }
                else
                {
                    _value = (_span.Days * 24);
                }
                break;

            case DateInterval.Minute:
                if (_span.Minutes > 0)
                {
                    _value = _span.Minutes;
                }
                else
                {
                    _value = (_span.Days * 24) * 60;
                }
                break;

            case DateInterval.Month:
                _value = CLng(_span.Days / 30); break;

            case DateInterval.Quarter:
                _value = (CLng(_span.Days / 30) / 3); break;

            case DateInterval.Second:
                if (_span.Seconds > 0)
                {
                    _value = _span.Seconds;
                }
                else
                {
                    _value = ((_span.Days * 24) * 60) * 60;
                }
                break;

            case DateInterval.Week:
            case DateInterval.WeekOfYear:
                _value = CLng(_span.Days / 7); break;

            case DateInterval.Year:
                _value = CLng(_span.Days / 365); break;

            default: break;
            }

            return(_value);
        }
 public SolarReport(DateInterval billingInterval, double powerGenerated)
 {
     this.billingInterval = billingInterval;
     this.powerGenerated  = powerGenerated;
 }
示例#38
0
 protected override LocalDate GetProperty1Value(DateInterval value) => value.Start;
 public SolarAndUtilityReport(DateInterval billingInterval, double powerGenerated, int powerBoughtOrSold, int powerCostCents) :
     base(billingInterval, powerGenerated)
 {
     this.powerBoughtOrSold = powerBoughtOrSold;
     this.powerCostCents    = powerCostCents;
 }
示例#40
0
 private static IEnumerable <DateTimeOffset> GetOccurrences(DateInterval interval, DatePeriod period, Calendar calendar, DateTimeOffset start, DateTimeOffset end, bool skipWeekends = true)
 {
     return(GetOccurrences(interval, period, calendar, start.DateTime, end.DateTime, skipWeekends).Select(occurrence => (DateTimeOffset)occurrence));
 }
示例#41
0
 public DateHistogramAggregationDescriptor <T> Interval(DateInterval interval) =>
 Assign(a => a.Interval = interval);
        private ResultSetBuilder EvaluateEquals(Expression expression)
        {
            if (expression.NodeType == ExpressionType.Equal ||
                expression.NodeType == ExpressionType.NotEqual)
            {
                var literal    = ExHelper.GetLiteralValue(expression, _parameters);
                var memberName = ExHelper.GetMemberName(expression, _itemType);

                IColumnMetadata column;
                try
                {
                    column = _journal.Metadata.GetColumnByPropertyName(memberName);
                }
                catch (NFSdbConfigurationException)
                {
                    throw QueryExceptionExtensions.ExpressionNotSupported(
                              string.Format("Column {0} does not exist", memberName), expression);
                }

                if (_journal.Metadata.TimestampColumnID == column.ColumnID)
                {
                    if (expression.NodeType == ExpressionType.Equal)
                    {
                        if (literal is long || literal is DateTime)
                        {
                            if (GetTimestamp(_journal.Metadata) != null &&
                                GetTimestamp(_journal.Metadata).PropertyName == memberName)
                            {
                                DateInterval filterInterval;
                                if (literal is long)
                                {
                                    var timestamp = (long)literal;
                                    filterInterval = new DateInterval(DateUtils.UnixTimestampToDateTime(timestamp),
                                                                      DateUtils.UnixTimestampToDateTime(timestamp + 1));
                                }
                                else
                                {
                                    var timestamp = (DateTime)literal;
                                    filterInterval = new DateInterval(timestamp,
                                                                      new DateTime(timestamp.Ticks + 1, timestamp.Kind));
                                }

                                var result = new ResultSetBuilder(_journal, _tx);
                                result.TimestampInterval(filterInterval);
                                return(result);
                            }
                        }
                    }
                }

                var res = new ResultSetBuilder(_journal, _tx);
                try
                {
                    if (literal != null)
                    {
                        if (expression.NodeType == ExpressionType.Equal)
                        {
                            ReflectionHelper.CallStaticPrivateGeneric("CreateColumnScan", this,
                                                                      column.DataType.Clazz, column, literal, res);
                        }
                        else if (expression.NodeType == ExpressionType.NotEqual)
                        {
                            ReflectionHelper.CallStaticPrivateGeneric("CreateColumnNotEqualScan", this,
                                                                      column.DataType.Clazz, column, literal, res);
                        }
                    }
                    else
                    {
                        if (expression.NodeType == ExpressionType.Equal)
                        {
                            ReflectionHelper.CallStaticPrivateGeneric("CreateColumnScan", this,
                                                                      column.DataType.Clazz, column, null, res);
                        }
                        else if (expression.NodeType == ExpressionType.NotEqual)
                        {
                            ReflectionHelper.CallStaticPrivateGeneric("CreateColumnNotEqualScan", this,
                                                                      column.DataType.Clazz, column, null, res);
                        }
                    }
                }
                catch (NFSdbQueryableNotSupportedException ex)
                {
                    throw QueryExceptionExtensions.ExpressionNotSupported(ex.Message, expression);
                }
                catch (InvalidCastException ex)
                {
                    throw QueryExceptionExtensions.ExpressionNotSupported(ex.Message, expression);
                }
                return(res);
            }

            throw new NotSupportedException(
                      string.Format("Unable to translate expression {0} to journal operation", expression));
        }
示例#43
0
        public static int DatePart(DateInterval Interval, DateTime DateValue, FirstDayOfWeek FirstDayOfWeekValue = 1, FirstWeekOfYear FirstWeekOfYearValue = 1)
        {
            DayOfWeek        firstDayOfWeek;
            CalendarWeekRule calendarWeekRule;

            switch (Interval)
            {
            case DateInterval.Year:
                return(CurrentCalendar.GetYear(DateValue));

            case DateInterval.Quarter:
                return(((DateValue.Month - 1) / 3) + 1);

            case DateInterval.Month:
                return(CurrentCalendar.GetMonth(DateValue));

            case DateInterval.DayOfYear:
                return(CurrentCalendar.GetDayOfYear(DateValue));

            case DateInterval.Day:
                return(CurrentCalendar.GetDayOfMonth(DateValue));

            case DateInterval.WeekOfYear:
                if (FirstDayOfWeekValue != FirstDayOfWeek.System)
                {
                    firstDayOfWeek = (DayOfWeek)(FirstDayOfWeekValue - 1);
                    break;
                }
                firstDayOfWeek = Utils.GetCultureInfo().DateTimeFormat.FirstDayOfWeek;
                break;

            case DateInterval.Weekday:
                return(Weekday(DateValue, FirstDayOfWeekValue));

            case DateInterval.Hour:
                return(CurrentCalendar.GetHour(DateValue));

            case DateInterval.Minute:
                return(CurrentCalendar.GetMinute(DateValue));

            case DateInterval.Second:
                return(CurrentCalendar.GetSecond(DateValue));

            default:
                throw new ArgumentException(Utils.GetResourceString("Argument_InvalidValue1", new string[] { "Interval" }));
            }
            switch (FirstWeekOfYearValue)
            {
            case FirstWeekOfYear.System:
                calendarWeekRule = Utils.GetCultureInfo().DateTimeFormat.CalendarWeekRule;
                break;

            case FirstWeekOfYear.Jan1:
                calendarWeekRule = CalendarWeekRule.FirstDay;
                break;

            case FirstWeekOfYear.FirstFourDays:
                calendarWeekRule = CalendarWeekRule.FirstFourDayWeek;
                break;

            case FirstWeekOfYear.FirstFullWeek:
                calendarWeekRule = CalendarWeekRule.FirstFullWeek;
                break;
            }
            return(CurrentCalendar.GetWeekOfYear(DateValue, calendarWeekRule, firstDayOfWeek));
        }
示例#44
0
        public override object GetContent()
        {
            var minDate = DateTime.MinValue;
            var maxDate = DateTime.MaxValue - TimeSpan.FromDays(1);
            var frDate  = Request.GetValidated("Fr", minDate);
            var toDate  = Request.GetValidated("To", maxDate, dt => dt >= frDate, Tr.PgTrns.Validation_NotBeforeFr);
            var amtFmt  = Request.GetValidated("AmtFmt", "#,0");

            _interval = new DateInterval(frDate.Date, toDate.Date + TimeSpan.FromDays(1) - TimeSpan.FromTicks(1));
            _account  = GetAccount("Acct");
            var subAccts    = _subaccts = Request.GetValidated("SubAccts", false);
            var showBalance = Request.GetValidated("ShowBal", false, val => !(val && _subaccts), Tr.PgTrns.Validation_ShowBalVsSubAccts);

            _subaccts &= _account.EnumChildren().Any();

            ReportTable table     = new ReportTable();
            var         colDate   = table.AddCol(Tr.PgTrns.ColDate);
            var         colDesc   = table.AddCol(Tr.PgTrns.ColDescription);
            var         colQty    = table.AddCol(Tr.PgTrns.ColQuantity);
            var         colCcy    = table.AddCol(Tr.PgTrns.ColCurrency);
            var         colBal    = table.AddCol(Tr.PgTrns.ColBalance);
            var         colAcct   = table.AddCol(Tr.PgTrns.ColAccount);
            var         colInBase = table.AddCol(Tr.PgTrns.ColInBaseCcy.Fmt(Program.CurFile.Book.BaseCurrencyId));

            if (!_subaccts)
            {
                table.Cols.Remove(colAcct);
            }
            if (showBalance)
            {
                table.Cols.Remove(colInBase);
            }
            else
            {
                table.Cols.Remove(colBal);
            }

            var splits = _account.EnumSplits(_subaccts);

            splits = splits.Where(split => split.Transaction.DatePosted >= frDate && split.Transaction.DatePosted <= toDate);
            splits = splits.OrderBy(split => split.Transaction);

            foreach (var split in splits)
            {
                var trn = split.Transaction;
                var row = table.AddRow();

                row.SetValue(colDate, trn.DatePosted.ToShortDateString());
                row.SetValue(colDesc, (split.Memo == null || split.Memo == "" || split.Memo == trn.Description)
                    ? trn.Description
                    : (trn.Description + " [" + split.Memo + "]"));
                row.SetValue(colQty, split.Quantity.ToString(amtFmt), ReportTable.CssClassNumber(split.Quantity));
                row.SetValue(colCcy, split.Account.Commodity.Identifier, "ccy_name ccy_" + split.Account.Commodity.Identifier.Replace(":", "_"));
                if (!showBalance)
                {
                    row.SetValue(colInBase, split.AmountConverted(Program.CurFile.Book.BaseCurrency).Quantity.ToString(amtFmt), ReportTable.CssClassNumber(split.Quantity));
                }

                if (showBalance)
                {
                    row.SetValue(colBal, split.AccountBalanceAfter.ToString(amtFmt), ReportTable.CssClassNumber(split.AccountBalanceAfter));
                }

                if (_subaccts)
                {
                    row.SetValue(colAcct, generateAcctPath(split.Account));
                }

                if (split.IsBalsnap)
                {
                    try { row.CssClass = split.AccountBalanceAfter == split.Balsnap ? "balsnap_ok" : "balsnap_wrong"; }
                    catch (GncBalsnapParseException) { row.CssClass = "balsnap_error"; }
                }
            }

            return(Ut.NewArray(
                       new P(Tr.PgMonthly.CurAccount, GetAccountBreadcrumbs("Acct", _account)),
                       new P(Tr.PgTrns.ModeCaption,
                             showBalance && !subAccts ? (object)new SPAN(Tr.PgTrns.ModeWithBalance)
            {
                class_ = "aw-current"
            } : new A(Tr.PgTrns.ModeWithBalance)
            {
                href = Request.Url.WithQuery("ShowBal", "true").WithoutQuery("SubAccts").ToHref()
            },
                             " · ",
                             !showBalance && subAccts ? (object)new SPAN(Tr.PgTrns.ModeWithSubaccts)
            {
                class_ = "aw-current"
            } : new A(Tr.PgTrns.ModeWithSubaccts)
            {
                href = Request.Url.WithoutQuery("ShowBal").WithQuery("SubAccts", "true").ToHref()
            }
                             ),
                       new P(Tr.PgTrns.RoundingCaption,
                             amtFmt == "#,0" ? (object)new SPAN(Tr.PgTrns.RoundingWhole)
            {
                class_ = "aw-current"
            } : new A(Tr.PgTrns.RoundingWhole)
            {
                href = Request.Url.WithoutQuery("AmtFmt").ToHref()
            },
                             " · ",
                             amtFmt == "#,0.00" ? (object)new SPAN(Tr.PgTrns.RoundingDecimals)
            {
                class_ = "aw-current"
            } : new A(Tr.PgTrns.RoundingDecimals)
            {
                href = Request.Url.WithQuery("AmtFmt", "#,0.00").ToHref()
            }
                             ),
                       new P(Tr.PgTrns.DateCaption,
                             (frDate == minDate && toDate == maxDate) ? (object)Tr.PgTrns.ShowingAll :
                             (frDate == minDate) ? Tr.PgTrns.ShowingOnOrBefore.FmtEnumerable(
                                 (object)Ut.NewArray <object>(new SPAN(toDate.ToShortDateString())
            {
                class_ = "filter_hilite"
            }, " (", new A(Tr.PgTrns.DateRemove)
            {
                href = Request.Url.WithoutQuery("To").ToHref()
            }, ")")
                                 ) :
                             (toDate == maxDate) ? Tr.PgTrns.ShowingOnOrAfter.FmtEnumerable(
                                 (object)Ut.NewArray <object>(new SPAN(frDate.ToShortDateString())
            {
                class_ = "filter_hilite"
            }, " (", new A(Tr.PgTrns.DateRemove)
            {
                href = Request.Url.WithoutQuery("Fr").ToHref()
            }, ")")
                                 ) :
                             Tr.PgTrns.ShowingBetween.FmtEnumerable(
                                 Ut.NewArray <object>(new SPAN(frDate.ToShortDateString())
            {
                class_ = "filter_hilite"
            }, " (", new A(Tr.PgTrns.DateRemove)
            {
                href = Request.Url.WithoutQuery("Fr").ToHref()
            }, ")"),
                                 Ut.NewArray <object>(new SPAN(toDate.ToShortDateString())
            {
                class_ = "filter_hilite"
            }, " (", new A(Tr.PgTrns.DateRemove)
            {
                href = Request.Url.WithoutQuery("To").ToHref()
            }, ")")
                                 )
                             ),
                       table.GetHtml()
                       ));
        }
示例#45
0
        /// <summary>
        /// Ported from subtotal_posts::report_subtotal
        /// </summary>
        public void ReportSubtotal(string specFmt = null, DateInterval interval = null)
        {
            if (!ComponentPosts.Any())
            {
                return;
            }

            Date?rangeStart  = interval != null ? interval.Start : null;
            Date?rangeFinish = interval != null ? interval.InclusiveEnd : null;

            if (!rangeStart.HasValue || !rangeFinish.HasValue)
            {
                foreach (Post post in ComponentPosts)
                {
                    Date date      = post.GetDate();
                    Date valueDate = post.ValueDate;

                    if (!rangeStart.HasValue || date < rangeStart)
                    {
                        rangeStart = date;
                    }
                    if (!rangeFinish.HasValue || valueDate > rangeFinish)
                    {
                        rangeFinish = valueDate;
                    }
                }
            }

            ComponentPosts.Clear();

            string outDate;

            if (!String.IsNullOrEmpty(specFmt))
            {
                outDate = TimesCommon.Current.FormatDate(rangeFinish.Value, FormatTypeEnum.FMT_CUSTOM, specFmt);
            }
            else if (!String.IsNullOrEmpty(DateFormat))
            {
                outDate = "- " + TimesCommon.Current.FormatDate(rangeFinish.Value, FormatTypeEnum.FMT_CUSTOM, DateFormat);
            }
            else
            {
                outDate = "- " + TimesCommon.Current.FormatDate(rangeFinish.Value);
            }

            Xact xact = Temps.CreateXact();

            xact.Payee = outDate;
            xact.Date  = rangeStart.Value;

            foreach (KeyValuePair <string, AcctValue> pair in Values)
            {
                FiltersCommon.HandleValue(
                    /* value=      */ pair.Value.Value,
                    /* account=    */ pair.Value.Account,
                    /* xact=       */ xact,
                    /* temps=      */ Temps,
                    /* handler=    */ (PostHandler)Handler,
                    /* date=       */ rangeFinish.Value,
                    /* act_date_p= */ false);
            }

            Values.Clear();
        }
示例#46
0
 public static long DateDiff(DateInterval Interval, System.DateTime Date1, System.DateTime Date2, FirstDayOfWeek DayOfWeek, FirstWeekOfYear WeekOfYear)
 {
 }
示例#47
0
        private static IEnumerable <DateTime> GetOccurrences(DateInterval interval, DatePeriod period, Calendar calendar,
                                                             DateTime start, DateTime end, bool skipWeekends = true)
        {
            var difference = DateSpan.GetDifference(interval, start, end) / period.Quantifier;

            if (start.Kind == DateTimeKind.Utc)
            {
                start = start.ToLocalTime();
            }

            for (var i = 0; i < difference; i++)
            {
                switch (period.Frequency)
                {
                case DatePeriodFrequency.Seconds:
                    var seconds = calendar.AddSeconds(start, period.Quantifier * i);
                    yield return(DeferOccurrenceFallingOnWeekend(calendar, seconds, skipWeekends));

                    break;

                case DatePeriodFrequency.Minutes:
                    var minutes = calendar.AddMinutes(start, period.Quantifier * i);
                    yield return(DeferOccurrenceFallingOnWeekend(calendar, minutes, skipWeekends));

                    break;

                case DatePeriodFrequency.Hours:
                    var hours = calendar.AddHours(start, period.Quantifier * i);
                    yield return(DeferOccurrenceFallingOnWeekend(calendar, hours, skipWeekends));

                    break;

                case DatePeriodFrequency.Days:
                    var days = calendar.AddDays(start, period.Quantifier * i);
                    yield return(DeferOccurrenceFallingOnWeekend(calendar, days, skipWeekends));

                    break;

                case DatePeriodFrequency.Weeks:
                    var weeks = calendar.AddWeeks(start, period.Quantifier * i);
                    yield return(DeferOccurrenceFallingOnWeekend(calendar, weeks, skipWeekends));

                    break;

                case DatePeriodFrequency.Months:
                    var months = calendar.AddMonths(start, period.Quantifier * i);
                    yield return(DeferOccurrenceFallingOnWeekend(calendar, months, skipWeekends));

                    break;

                case DatePeriodFrequency.Years:
                    var years = calendar.AddYears(start, period.Quantifier * i);
                    yield return(DeferOccurrenceFallingOnWeekend(calendar, years, skipWeekends));

                    break;

                default:
                    throw new ArgumentException("Frequency");
                }
            }
        }
示例#48
0
 public static int DatePart(DateInterval Interval, System.DateTime DateValue, FirstDayOfWeek FirstDayOfWeekValue, FirstWeekOfYear FirstWeekOfYearValue)
 {
 }
示例#49
0
 public virtual void SupportsUnion(DateInterval dateInterval)
 {
     SupportsPropertyOrMethod(x => x.Union(dateInterval));
 }
    public static long DateDiff(DateInterval interval, DateTime dt1, DateTime dt2, DayOfWeek eFirstDayOfWeek)
    {
        if (interval == DateInterval.Year)
        {
            return(dt2.Year - dt1.Year);
        }

        if (interval == DateInterval.Month)
        {
            return((dt2.Month - dt1.Month) + (12 * (dt2.Year - dt1.Year)));
        }

        TimeSpan ts = dt2 - dt1;

        if (interval == DateInterval.Day || interval == DateInterval.DayOfYear)
        {
            return(Round(ts.TotalDays));
        }

        if (interval == DateInterval.Hour)
        {
            return(Round(ts.TotalHours));
        }

        if (interval == DateInterval.Minute)
        {
            return(Round(ts.TotalMinutes));
        }

        if (interval == DateInterval.Second)
        {
            return(Round(ts.TotalSeconds));
        }

        if (interval == DateInterval.Weekday)
        {
            return(Round(ts.TotalDays / 7.0));
        }

        if (interval == DateInterval.WeekOfYear)
        {
            while (dt2.DayOfWeek != eFirstDayOfWeek)
            {
                dt2 = dt2.AddDays(-1);
            }
            while (dt1.DayOfWeek != eFirstDayOfWeek)
            {
                dt1 = dt1.AddDays(-1);
            }
            ts = dt2 - dt1;
            return(Round(ts.TotalDays / 7.0));
        }

        if (interval == DateInterval.Quarter)
        {
            double d1Quarter = GetQuarter(dt1.Month);
            double d2Quarter = GetQuarter(dt2.Month);
            double d1        = d2Quarter - d1Quarter;
            double d2        = (4 * (dt2.Year - dt1.Year));
            return(Round(d1 + d2));
        }

        return(0);
    }
示例#51
0
        public void Union_NullInterval_Throws()
        {
            var value = new DateInterval(new LocalDate(100), new LocalDate(200));

            Assert.Throws <ArgumentNullException>(() => value.Union(null));
        }
示例#52
0
        public static AggregationContainerDescriptor <T> IntoDateHistogram <T>(this AggregationContainerDescriptor <T> innerAggregation,
                                                                               Expression <Func <T, object> > fieldGetter, DateInterval interval) where T : class
        {
            AggregationContainerDescriptor <T> v = new AggregationContainerDescriptor <T>();
            var fieldName = GetName(fieldGetter);

            v.DateHistogram(fieldName, dr =>
            {
                DateHistogramAggregationDescriptor <T> dateAggDesc = new DateHistogramAggregationDescriptor <T>();
                dateAggDesc.Field(fieldGetter).Interval(interval);
                return(dateAggDesc.Aggregations(x => innerAggregation));
            });

            return(v);
        }
示例#53
0
 // Methods
 public static System.DateTime DateAdd(DateInterval Interval, double Number, System.DateTime DateValue)
 {
 }
 /// <inheritdoc cref="IDateHistogramGroupSource.FixedInterval"/>
 public DateHistogramGroupSourceDescriptor <T> FixedInterval(DateInterval dateInterval) => Assign(dateInterval, (a, v) => a.FixedInterval = v);
示例#55
0
文件: File.cs 项目: Gavamot/FTPSync
 public bool IsInInterval(DateInterval interval)
 {
     return(Pdt >= interval.Start && Pdt <= interval.End);
 }
 /// <inheritdoc cref="IDateHistogramGroupSource.CalendarInterval"/>
 public DateHistogramGroupSourceDescriptor <T> CalendarInterval(DateInterval dateInterval) => Assign(dateInterval, (a, v) => a.CalendarInterval = v);
 public static long DateDiff(DateInterval interval, DateTime dt1, DateTime dt2)
 {
     return(DateDiff(interval, dt1, dt2, System.Globalization.DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek));
 }
示例#58
0
 public static bool IsInCurrentDateInterval(this DateTime dateTime, DateTime selectedDate, DateInterval dateInterval)
 {
     if (dateInterval == DateInterval.Day)
     {
         return(dateTime.Date == selectedDate.Date);
     }
     else if (dateInterval == DateInterval.Week)
     {
         return(dateTime.Date >= selectedDate.SearchedDayOfWeek(DayOfWeek.Monday).Date&& dateTime.Date <= selectedDate.SearchedDayOfWeek(DayOfWeek.Sunday).Date);
     }
     else if (dateInterval == DateInterval.Month)
     {
         return(dateTime.Date >= selectedDate.SearchFirstDayOfMonth().Date&& dateTime.Date <= selectedDate.SearchLastDayOfMonth().Date);
     }
     else if (dateInterval == DateInterval.Year)
     {
         return(dateTime.Date >= selectedDate.SearchFirstDayOfYear().Date&& dateTime.Date <= selectedDate.SearchLastDayOfYear().Date);
     }
     else if (dateInterval == DateInterval.All)
     {
         return(true);
     }
     else
     {
         throw new Exception("Wrong parameters were passed");
     }
 }
        private ResultSetBuilder EvaluateCompare(Expression exp)
        {
            var memberName = ExHelper.GetMemberName(exp, _itemType);
            var literal    = ExHelper.GetLiteralValue(exp, _parameters);

            var columnMetadata = GetTimestamp(_journal.Metadata);

            if (columnMetadata != null &&
                string.Equals(columnMetadata.PropertyName, memberName, StringComparison.OrdinalIgnoreCase) &&
                (literal is long || literal is DateTime))
            {
                DateInterval filterInterval;
                var          nodeType = exp.NodeType;
                if (exp.GetLeft().NodeType == ExpressionType.Constant)
                {
                    nodeType = InvertComarison(nodeType);
                }

                switch (nodeType)
                {
                case ExpressionType.GreaterThan:
                    var timestamp = literal is long
                                    ?DateUtils.UnixTimestampToDateTime((long)literal + 1)
                                        : ((DateTime)literal).AddTicks(1);

                    filterInterval = DateInterval.From(timestamp);
                    break;

                case ExpressionType.GreaterThanOrEqual:
                    timestamp = literal is long
                                ?DateUtils.UnixTimestampToDateTime((long)literal)
                                    : (DateTime)literal;

                    filterInterval = DateInterval.From(timestamp);
                    break;

                case ExpressionType.LessThan:
                    timestamp = literal is long
                                ?DateUtils.UnixTimestampToDateTime((long)literal)
                                    : (DateTime)literal;

                    filterInterval = DateInterval.To(timestamp);
                    break;

                case ExpressionType.LessThanOrEqual:
                    timestamp = literal is long
                                ?DateUtils.UnixTimestampToDateTime((long)literal + 1)
                                    : ((DateTime)literal).AddTicks(1);

                    filterInterval = DateInterval.To(timestamp);
                    break;

                default:
                    throw QueryExceptionExtensions.ExpressionNotSupported(string.Format(
                                                                              "Timestamp column operation {0} is not supported. Supported operations are <, >, <=, >=",
                                                                              nodeType), exp);
                }

                var result = new ResultSetBuilder(_journal, _tx);
                result.TimestampInterval(filterInterval);
                return(result);
            }
            throw QueryExceptionExtensions.ExpressionNotSupported(
                      "Comparison is supported for timestamp column only. Unable to bind '{0} to journal query operation",
                      exp);
        }
示例#60
0
 public static AggregationContainerDescriptor <T> DateHistogram <T>(this AggregationContainerDescriptor <T> agg,
                                                                    Expression <Func <T, object> > fieldGetter, DateInterval dateInterval) where T : class
 {
     return(agg.DateHistogram(GetName(fieldGetter), x => x.Field(fieldGetter).Interval(dateInterval)));
 }