示例#1
0
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var currentTime    = DateTime.UtcNow;
            var timeDifference = DateTimeSpan.CompareDates(currentTime, (DateTime)value);

            if (timeDifference.Years > 0)
            {
                return(string.Format("{0} Year{1} ago", timeDifference.Years, timeDifference.Years > 1 ? "s" : ""));
            }
            else if (timeDifference.Months > 0)
            {
                return(string.Format("{0} Month{1} ago", timeDifference.Months, timeDifference.Months > 1 ? "s" : ""));
            }
            else if (timeDifference.Days > 0)
            {
                return(string.Format("{0} Day{1} ago", timeDifference.Days, timeDifference.Days > 1 ? "s" : ""));
            }
            else if (timeDifference.Hours > 0)
            {
                return(string.Format("{0} Hour{1} ago", timeDifference.Hours, timeDifference.Hours > 1 ? "s" : ""));
            }
            else if (timeDifference.Minutes > 0)
            {
                return(string.Format("{0} Minute{1} ago", timeDifference.Minutes, timeDifference.Minutes > 1 ? "s" : ""));
            }
            else
            {
                return("Just Now");
            }
        }
示例#2
0
        public void Execute(IJobExecutionContext context)
        {
            DateTime today = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, 0);

            using (DataContext _db = new DataContext())
            {
                _db.Database.CommandTimeout = 6000;
                using (DbContextTransaction tran = _db.Database.BeginTransaction(System.Data.IsolationLevel.Serializable))
                {
                    try
                    {
                        foreach (var card in _db.Cards.Where(c => c.CardStatus != CardStatus.Canceled && c.CardStatus != CardStatus.Blocked && c.CardStatus != CardStatus.Paused))
                        {
                            var dateSpan = DateTimeSpan.CompareDates(card.Tdate, DateTime.Now);
                            if (dateSpan.Months == 0 && dateSpan.Days == 1)
                            {
                                card.LastPauseType      = 0;
                                card.PauseFreeMonthUsed = false;
                                _db.Entry(card).State   = System.Data.Entity.EntityState.Modified;
                                _db.SaveChanges();
                            }
                        }

                        tran.Commit();
                    }
                    catch (Exception)
                    {
                        tran.Rollback();
                    }
                }
            }
        }
        public void JudgingStringIsNullableDateTimeSpanTypeWithIgnoreCaseTest()
        {
            var          type         = typeof(DateTimeSpan);
            var          nullableType = typeof(DateTimeSpan?);
            var          today        = DateTime.Today.AddDays(-10);
            var          now          = DateTime.Now;
            DateTimeSpan span         = now - today;
            var          text0        = span.ToString("c");
            var          text1        = span.ToString("g");
            var          text2        = span.ToString("G");

            text0.Is(type, Context).ShouldBeTrue();
            text1.Is(type, Context).ShouldBeTrue();
            text2.Is(type, Context).ShouldBeTrue();

            text0.Is(nullableType, Context).ShouldBeTrue();
            text1.Is(nullableType, Context).ShouldBeTrue();
            text2.Is(nullableType, Context).ShouldBeTrue();

            text0.IsNullable(type, Context).ShouldBeTrue();
            text1.IsNullable(type, Context).ShouldBeTrue();
            text2.IsNullable(type, Context).ShouldBeTrue();

            text0.IsNullable(nullableType, Context).ShouldBeTrue();
            text1.IsNullable(nullableType, Context).ShouldBeTrue();
            text2.IsNullable(nullableType, Context).ShouldBeTrue();
        }
示例#4
0
        private static int GetMonthDifference(DateTime date1, DateTime date2)
        {
            // Note: it doesn't matter which dates comes before the other.
            var dateSpan = DateTimeSpan.CompareDates(date1, date2);

            return((dateSpan.Years * 12) + dateSpan.Months);
        }
示例#5
0
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var currentTime = DateTime.UtcNow;

            if (((DateTime)value).Year == 1)
            {
                return("the dawn of reddit");
            }
            var timeDifference = DateTimeSpan.CompareDates(currentTime, (DateTime)value);

            if (timeDifference.Years > 0)
            {
                return(string.Format("{0} year{1} ago", timeDifference.Years, timeDifference.Years > 1 ? "s" : ""));
            }
            else if (timeDifference.Months > 0)
            {
                return(string.Format("{0} month{1} ago", timeDifference.Months, timeDifference.Months > 1 ? "s" : ""));
            }
            else if (timeDifference.Days > 0)
            {
                return(string.Format("{0} day{1} ago", timeDifference.Days, timeDifference.Days > 1 ? "s" : ""));
            }
            else if (timeDifference.Hours > 0)
            {
                return(string.Format("{0} hour{1} ago", timeDifference.Hours, timeDifference.Hours > 1 ? "s" : ""));
            }
            else if (timeDifference.Minutes > 0)
            {
                return(string.Format("{0} minute{1} ago", timeDifference.Minutes, timeDifference.Minutes > 1 ? "s" : ""));
            }
            else
            {
                return("just now");
            }
        }
示例#6
0
        public static string DiffForHumans(this DateTime dateTime)
        {
            var time = DateTimeSpan.CompareDates(dateTime, DateTime.UtcNow);

            if (time.Years != 0)
            {
                return($"{time.Years} years ago");
            }
            if (time.Months != 0)
            {
                return($"{time.Months} months ago");
            }
            if (time.Days != 0)
            {
                return($"{time.Days} days ago");
            }
            if (time.Hours != 0)
            {
                return($"{time.Hours} hours ago");
            }
            if (time.Minutes != 0)
            {
                return($"{time.Minutes} minutes ago");
            }
            return("Just now");
        }
示例#7
0
        public List <ChartItem> DrawChart(List <int> hardwareId)
        {
            List <ChartItem> allCharts = new List <ChartItem>();

            for (int i = 0; i < hardwareId.Count; i++)
            {
                var currentBrand = Hardware.FirstOrDefault(x => x.ConfigId == hardwareId[i]).Brand;
                var currentModel = Hardware.FirstOrDefault(x => x.ConfigId == hardwareId[i]).Model;

                DateTime today           = DateTime.Today;
                DateTime latestDate      = Transactions.Where(x => x.Brand == currentBrand && x.Model == currentModel).Max(x => x.Date);
                var      datetime        = DateTimeSpan.CompareDates(latestDate, today);
                int      monthDifference = datetime.Years * 12 + datetime.Months;

                allCharts.Add(new ChartItem
                {
                    Label       = $"{currentBrand.ToString()} {currentModel}",
                    Fill        = false,
                    BorderWidth = 1,
                    LstData     = ComputeForecast(hardwareId[i], (12 + monthDifference))
                });
            }

            return(allCharts);
        }
示例#8
0
        public List <ForecastResult> GenerateFutureForecast(int month = 12)
        {
            DateTime     today        = DateTime.Today;
            DateTime     lastDate     = m_observations.Max(x => x.Date);
            DateTimeSpan dateTimeSpan = DateTimeSpan.CompareDates(today, lastDate);
            int          difference   = (dateTimeSpan.Years * 12) + dateTimeSpan.Months;

            month += difference;

            for (int i = 0; i < month; i++)
            {
                // Adds new observation with date which is 1 month greater than the last object in m_observations;
                m_observations.Add(new Observation(m_observations[m_observations.Count - 1].Date.AddMonths(1)));
            }

            for (int i = 0; i < m_observations.Count; i++)
            {
                if (m_observations[i].Seasonality == null)
                {
                    m_observations[i].Seasonality = Algorithm.CalculateSeasonality(m_observations, i);
                    m_observations[i].Trend       = Algorithm.CalculateTrend(m_observations, i);
                    m_observations[i].Forecast    = Algorithm.CalculateForecast(m_observations, i);
                }
            }

            return(m_observations.Select(x => new ForecastResult(x.Date, x.Forecast.Value)).ToList());
        }
示例#9
0
        private List <ChartTransaction> ComputeForecast(int id, int forecastMonths = 12)
        {
            List <ChartTransaction> transactions = new List <ChartTransaction>();

            Brand  currentBrand = Hardware.FirstOrDefault(x => x.ConfigId == id).Brand;
            string currentModel = Hardware.FirstOrDefault(x => x.ConfigId == id).Model;

            TimeSeriesPrediction prediction = new TimeSeriesPrediction(Transactions, currentBrand, currentModel);

            prediction.GenerateFutureForecast(forecastMonths);

            DateTime today = DateTime.Today;

            foreach (Phone p in prediction.PhoneCollection.Phones)
            {
                DateTime currentDate    = p.Date;
                var      datetime       = DateTimeSpan.CompareDates(currentDate, today);
                int      yearDifference = datetime.Years;

                if (yearDifference <= 2)
                {
                    this.AddTransactionToRecord(id, new ChartTransaction {
                        Date = p.Date, Price = p.Forecast.Value
                    });
                    transactions.Add(new ChartTransaction
                    {
                        Date  = p.Date,
                        Price = p.Forecast.Value
                    });
                }
            }

            return(transactions);
        }
示例#10
0
        protected override void Execute(CodeActivityContext context)
        {
            String DateS1 = Date1String.Get(context);
            String DateS2 = Date2String.Get(context);
            Dictionary <String, Int32> dict = new Dictionary <string, int>();
            String format = Format.Get(context);

            if (String.IsNullOrEmpty(format))
            {
                format = "dd/MM/yyyy";
            }
            DateTime DT1 = DateTime.ParseExact(DateS1, format, null);
            DateTime DT2 = DateTime.ParseExact(DateS2, format, null);

            DateTimeSpan dateSpan = DateTimeSpan.CompareDates(DT1, DT2);

            dict["Years"]        = dateSpan.Years;
            dict["Months"]       = dateSpan.Months;
            dict["Days"]         = dateSpan.Days;
            dict["Hours"]        = dateSpan.Hours;
            dict["Minutes"]      = dateSpan.Minutes;
            dict["Seconds"]      = dateSpan.Seconds;
            dict["Milliseconds"] = dateSpan.Milliseconds;

            Difference.Set(context, dict);
        }
示例#11
0
        public bool CanBeReserved(DateTimeSpan requestedDates, int numberOfDaysGap)
        {
            // Find the booking dates before and after our current
            var firstPastReservation   = Reservations.Where(kvp => kvp.Key <= requestedDates.EndDate).Select(kvp => kvp.Value).LastOrDefault();
            var firstFutureReservation = Reservations.Where(kvp => kvp.Key >= requestedDates.EndDate).Select(kvp => kvp.Value).FirstOrDefault();

            if (firstPastReservation != null && requestedDates.Overlaps(firstPastReservation.Span))
            {
                // The reservation overlaps with the previous reservation
                return(false);
            }
            else if (firstFutureReservation != null && requestedDates.Overlaps(firstFutureReservation.Span))
            {
                // The reservation overlaps with the next reservation
                return(false);
            }
            else if (firstPastReservation != null && firstPastReservation.EndDate.WillCreateGap(requestedDates.StartDate, numberOfDaysGap))
            {
                // The reservation would create a gap
                return(false);
            }
            else if (firstFutureReservation != null && firstFutureReservation.StartDate.WillCreateGap(requestedDates.EndDate, numberOfDaysGap))
            {
                // The reservation would create a gap
                return(false);
            }

            // Nothing disqualifies this site, so we can book it
            return(true);
        }
        public void JudgingStringIsNullableDateTimeSpanTypeByGenericTypeAndWithIgnoreCaseTest()
        {
            var          today = DateTime.Today.AddDays(-10);
            var          now   = DateTime.Now;
            DateTimeSpan span  = now - today;
            var          text0 = span.ToString("c");
            var          text1 = span.ToString("g");
            var          text2 = span.ToString("G");

            text0.Is <DateTimeSpan>(Context).ShouldBeTrue();
            text1.Is <DateTimeSpan>(Context).ShouldBeTrue();
            text2.Is <DateTimeSpan>(Context).ShouldBeTrue();

            text0.Is <DateTimeSpan?>(Context).ShouldBeTrue();
            text1.Is <DateTimeSpan?>(Context).ShouldBeTrue();
            text2.Is <DateTimeSpan?>(Context).ShouldBeTrue();

            text0.IsNullable <DateTimeSpan>(Context).ShouldBeTrue();
            text1.IsNullable <DateTimeSpan>(Context).ShouldBeTrue();
            text2.IsNullable <DateTimeSpan>(Context).ShouldBeTrue();

            text0.IsNullable <DateTimeSpan?>(Context).ShouldBeTrue();
            text1.IsNullable <DateTimeSpan?>(Context).ShouldBeTrue();
            text2.IsNullable <DateTimeSpan?>(Context).ShouldBeTrue();
        }
        private List <int> AutogenerateMissingDataIfPossible(List <int> selectedPhoneIds, int months = 3)
        {
            List <int> eligibleIds = selectedPhoneIds;

            DateTime today        = DateTime.Today;
            int      currentMonth = DateTime.Today.Month;
            int      currentYear  = DateTime.Today.Year;

            foreach (int id in selectedPhoneIds)
            {
                Brand  selectedBrand = Hardware.FirstOrDefault(x => x.ConfigId == id).Brand;
                string selectedModel = Hardware.FirstOrDefault(x => x.ConfigId == id).Model;

                DateTime latestDate      = Phones.Where(x => x.Brand == selectedBrand && x.Model == selectedModel).Max(x => x.Date);
                var      datetime        = DateTimeSpan.CompareDates(latestDate, today);
                int      monthDifference = datetime.Years * 12 + datetime.Months;

                // Remove id if latest date cannot be found or the gap is too big
                if (latestDate == null || monthDifference > 3)
                {
                    eligibleIds.RemoveAll(x => x == id);
                    Errors.Add($"{selectedBrand} {selectedModel} - Data for the last {monthDifference} months is unavailable.");
                    Errors = Errors.Distinct().ToList();
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"Generating data");

                    TimeSeriesPrediction prediction = new TimeSeriesPrediction(Phones, selectedBrand, selectedModel);
                    prediction.GenerateFutureForecast(monthDifference);
                }
            }

            return(new List <int>());
        }
        public static bool HasEnoughTransactions(List <Item> list, Brand brand, string model)
        {
            List <Item> transactions = list.Where(m => m.Brand == brand).Where(m => m.Model == model).ToList();


            if (transactions.Count() <= 1 || transactions == null)
            {
                return(false);
            }

            DateTime earliestDate    = transactions.Select(m => m.Date).Min();
            DateTime latestDate      = transactions.Select(m => m.Date).Max();
            var      datetime        = DateTimeSpan.CompareDates(earliestDate, latestDate);
            int      monthDifference = datetime.Years * 12 + datetime.Months;

            System.Diagnostics.Debug.WriteLine($"DATE: {earliestDate.ToString()} - {latestDate.ToString()} = {monthDifference}");

            if (monthDifference < 24)
            {
                return(false);
            }
            if (transactions.Count() < ((monthDifference / 100) * 90))
            {
                return(false);
            }

            return(true);
        }
        public List <ChartItem> DrawChart(List <int> hardwareId)
        {
            List <ChartItem> allCharts = new List <ChartItem>();


            // Itterates through all passed id
            for (int i = 0; i < hardwareId.Count; i++)
            {
                // Find brand and model corresponding to id
                var currentBrand = Hardware.FirstOrDefault(m => m.ConfigId == hardwareId[i]).Brand;
                var currentModel = Hardware.FirstOrDefault(m => m.ConfigId == hardwareId[i]).Model;

                // The constructor already removes phones where gap between last transaction and today is more than ALLOWED_TRANSACTION_GAP_MONTHS
                // I don't need to validate here, it will always be less then that specified month gap.
                DateTime today           = DateTime.Today;
                DateTime latestDate      = Phones.Where(x => x.Brand == currentBrand && x.Model == currentModel).Max(x => x.Date);
                var      datetime        = DateTimeSpan.CompareDates(latestDate, today);
                int      monthDifference = datetime.Years * 12 + datetime.Months;

                // If there are enough transactions -> draws a chart and computers a forecasted price
                allCharts.Add(new ChartItem
                {
                    Label       = $"{currentBrand.ToString()} {currentModel}",
                    Fill        = false,
                    BorderWidth = 1,
                    // Computers price forecast. Returns a list of objects containing purchase date and price.
                    LstData = ComputeForecast(hardwareId[i], (FutureForecastMonths + monthDifference))
                });
            }

            return(allCharts);
        }
示例#16
0
        /// <summary>
        ///     Obtiene los datos generales de un derechohabiente
        /// </summary>
        /// <param name="isssteNumber">Numero de ISSSTE del derechohabiente a consultar</param>
        /// <returns>Datos generales del derechohabiente</returns>
        public async Task <EntitleSipeInformation> GetEntitleByNoIsssteAsync(string isssteNumber)
        {
            var token = GetToken();

            var baseAddress = ServiceBaseUrl + String.Format(EntitleByNoIsssteInfoUrl, isssteNumber);

            var http = BuildHttpClient(baseAddress, token);

            var response = await http.GetAsync(baseAddress);

            response.EnsureSuccessStatusCode();

            var json = await response.Content.ReadAsStringAsync();

            var directo = JsonConvert.DeserializeObject <List <EntitleSipeInformation> >(json);

            var firstDirecto = directo.FirstOrDefault();

            if (firstDirecto != null)
            {
                firstDirecto.Age =
                    DateTimeSpan.CompareDates(Convert.ToDateTime(firstDirecto.BirthDate), DateTime.Now).Years;
            }

            return(firstDirecto);
        }
示例#17
0
        /// <summary>
        ///     Obtiene los datos generales de los beneficiarios
        /// </summary>
        /// <param name="issstenumber">Numero de ISSSTE del derechohabiente a consultar</param>
        /// <returns>Datos generales de los beneficiarios</returns>
        public async Task <List <BeneficiarySipeInformation> > GetBeneficiariesByNoIsssteAsync(string issstenumber)
        {
            var token = GetToken();

            var baseAddress = ServiceBaseUrl + String.Format(BeneficiariesInfoUrl, issstenumber);

            var http = BuildHttpClient(baseAddress, token);

            var response = await http.GetAsync(baseAddress);

            response.EnsureSuccessStatusCode();

            var json = await response.Content.ReadAsStringAsync();

            var indirecto = JsonConvert.DeserializeObject <List <BeneficiarySipeInformation> >(json);

            foreach (var beneficiary in indirecto)
            {
                beneficiary.Age = DateTimeSpan.CompareDates(Convert.ToDateTime(beneficiary.BirthDate), DateTime.Now);

                beneficiary.AgeYears = beneficiary.Age.Years;
            }

            return(indirecto.OrderByDescending(o => o.BirthDate).ToList());
        }
示例#18
0
        public void DateTimeSpanParsing()
        {
            Assert.AreEqual(new DateTimeSpan(1, 1, 1, 1, 1, 1, 1), DateTimeSpan.Parse("1 year 1 month 1 week 1 day 1 hour 1 minute 1 second"));
            Assert.AreEqual(new DateTimeSpan(0, 1, 1, 1, 1, 1, 1), DateTimeSpan.Parse("1 month 1 week 1 day 1 hour 1 minute 1 second"));
            Assert.AreEqual(new DateTimeSpan(0, 0, 1, 1, 1, 1, 1), DateTimeSpan.Parse("1 week 1 day 1 hour 1 minute 1 second"));
            Assert.AreEqual(new DateTimeSpan(0, 0, 0, 1, 1, 1, 1), DateTimeSpan.Parse("1 day 1 hour 1 minute 1 second"));
            Assert.AreEqual(new DateTimeSpan(0, 0, 0, 0, 1, 1, 1), DateTimeSpan.Parse("1 hour 1 minute 1 second"));
            Assert.AreEqual(new DateTimeSpan(0, 0, 0, 0, 0, 1, 1), DateTimeSpan.Parse("1 minute 1 second"));
            Assert.AreEqual(new DateTimeSpan(0, 0, 0, 0, 0, 0, 1), DateTimeSpan.Parse("1 second"));

            Assert.AreEqual(new DateTimeSpan(10, 1, 1, 1, 1, 1, 1), DateTimeSpan.Parse("10 year 1 month 1 week 1 day 1 hour 1 minute 1 second"));
            Assert.AreEqual(new DateTimeSpan(0, 10, 1, 1, 1, 1, 1), DateTimeSpan.Parse("10 month 1 week 1 day 1 hour 1 minute 1 second"));
            Assert.AreEqual(new DateTimeSpan(0, 0, 10, 1, 1, 1, 1), DateTimeSpan.Parse("10 week 1 day 1 hour 1 minute 1 second"));
            Assert.AreEqual(new DateTimeSpan(0, 0, 0, 10, 1, 1, 1), DateTimeSpan.Parse("10 day 1 hour 1 minute 1 second"));
            Assert.AreEqual(new DateTimeSpan(0, 0, 0, 0, 10, 1, 1), DateTimeSpan.Parse("10 hour 1 minute 1 second"));
            Assert.AreEqual(new DateTimeSpan(0, 0, 0, 0, 0, 10, 1), DateTimeSpan.Parse("10 minute 1 second"));
            Assert.AreEqual(new DateTimeSpan(0, 0, 0, 0, 0, 0, 10), DateTimeSpan.Parse("10 second"));

            Assert.AreEqual(new DateTimeSpan(1, 1, 1, 1, 1, 1, 1), DateTimeSpan.Parse("1year 1month 1week 1day 1hour 1minute 1second"));
            Assert.AreEqual(new DateTimeSpan(0, 1, 1, 1, 1, 1, 1), DateTimeSpan.Parse("1month 1week 1day 1hour 1minute 1second"));
            Assert.AreEqual(new DateTimeSpan(0, 0, 1, 1, 1, 1, 1), DateTimeSpan.Parse("1week 1day 1hour 1minute 1second"));
            Assert.AreEqual(new DateTimeSpan(0, 0, 0, 1, 1, 1, 1), DateTimeSpan.Parse("1day 1hour 1minute 1second"));
            Assert.AreEqual(new DateTimeSpan(0, 0, 0, 0, 1, 1, 1), DateTimeSpan.Parse("1hour 1minute 1second"));
            Assert.AreEqual(new DateTimeSpan(0, 0, 0, 0, 0, 1, 1), DateTimeSpan.Parse("1minute 1second"));
            Assert.AreEqual(new DateTimeSpan(0, 0, 0, 0, 0, 0, 1), DateTimeSpan.Parse("1second"));
        }
        public void Should_get_formatted_date()
        {
            var span = new DateTimeSpan(new DateTime(2000, 1, 1, 8, 30, 0),
                                        new DateTime(2000, 1, 1, 17, 0, 0), "cst");

            span.ToString().ShouldEqual("1/1/2000 8:30 - 5:00 PM cst");
        }
示例#20
0
        public ActionResult DeleteConfirmed(int id)
        {
            DateTimeSpan dateTimeSpan = db.DateTimeSpans.Find(id);

            db.DateTimeSpans.Remove(dateTimeSpan);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
示例#21
0
    public static DateTimeSpan CompareDates(DateTime StartDate, DateTime EndDate)
    {
        DateTimeSpan R = new DateTimeSpan();

        if (StartDate.Equals(EndDate))
        {
            return(new DateTimeSpan());
        }
        bool Later;

        if (Later = StartDate > EndDate)
        {
            DateTime D = StartDate;
            StartDate = EndDate;
            EndDate   = D;
        }

        // Calculate Date Stuff
        for (DateTime D = StartDate.AddYears(1); D < EndDate; D = D.AddYears(1), R.Years++)
        {
            ;
        }
        if (R.Years > 0)
        {
            StartDate = StartDate.AddYears(R.Years);
        }
        for (DateTime D = StartDate.AddMonths(1); D < EndDate; D = D.AddMonths(1), R.Months++)
        {
            ;
        }
        if (R.Months > 0)
        {
            StartDate = StartDate.AddMonths(R.Months);
        }
        for (DateTime D = StartDate.AddDays(1); D < EndDate; D = D.AddDays(1), R.Days++)
        {
            ;
        }
        if (R.Days > 0)
        {
            StartDate = StartDate.AddDays(R.Days);
        }

        // Calculate Time Stuff
        TimeSpan T1 = EndDate - StartDate;

        R.Hours        = T1.Hours;
        R.Minutes      = T1.Minutes;
        R.Seconds      = T1.Seconds;
        R.Milliseconds = T1.Milliseconds;

        // Return answer. Negate values if the Start Date was later than the End Date
        if (Later)
        {
            return(new DateTimeSpan(-R.Years, -R.Months, -R.Days, -R.Hours, -R.Minutes, -R.Seconds, -R.Milliseconds));
        }
        return(R);
    }
示例#22
0
        public void TimeTest()
        {
            DateTimeOffset offset = new DateTimeOffset(new DateTime(2021, 8, 30));

            TestValue(offset);
            DateTimeSpan span = new DateTimeSpan(offset, new TimeSpan(4, 33, 0));

            TestValue(span);
        }
示例#23
0
 public static DateTimeSpan CompareDates(DateTime date1, DateTime date2)
 {
     if (date2 < date1)
         {
             var sub = date1;
             date1 = date2;
             date2 = sub;
         }
         DateTime current = date1;
         int years = 0;
         int months = 0;
         int days = 0;
         Phase phase = Phase.Years;
         DateTimeSpan span = new DateTimeSpan();
         while (phase != Phase.Done)
         {
             switch (phase)
             {
                 case Phase.Years:
                     if (current.AddYears(years + 1) > date2)
                     {
                         phase = Phase.Months;
                         current = current.AddYears(years);
                     }
                     else
                     {
                         years++;
                     }
                     break;
                 case Phase.Months:
                     if (current.AddMonths(months + 1) > date2)
                     {
                         phase = Phase.Days;
                         current = current.AddMonths(months);
                     }
                     else
                     {
                         months++;
                     }
                     break;
                 case Phase.Days:
                     if (current.AddDays(days + 1) > date2)
                     {
                         current = current.AddDays(days);
                         var timespan = date2 - current;
                         span = new DateTimeSpan(years, months, days, timespan.Hours, timespan.Minutes, timespan.Seconds, timespan.Milliseconds);
                         phase = Phase.Done;
                     }
                     else
                     {
                         days++;
                     }
                     break;
             }
         }
         return span;
 }
示例#24
0
 public ActionResult Edit([Bind(Include = "Id,DateTimeName")] DateTimeSpan dateTimeSpan)
 {
     if (ModelState.IsValid)
     {
         db.Entry(dateTimeSpan).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(dateTimeSpan));
 }
        public static int GetStratum(DateTimeSpan kidSpan, List <StratumModel> stratums)
        {
            var stratumId = 0;
            var years     = kidSpan.Years;
            var months    = kidSpan.Months;
            var days      = kidSpan.Days;

            var isLimitMonth = false;

            foreach (var stratum in stratums)
            {
                isLimitMonth = false;

                if (years >= stratum.StartAge && years <= stratum.EndAge)
                {
                    if (months >= stratum.StartMonths && months <= stratum.EndMonths)
                    {
                        isLimitMonth = months == stratum.EndMonths;
                        if (days >= stratum.StartDays && days <= stratum.EndDays)
                        {
                            stratumId = stratum.StratumId;
                            break;
                        }
                        if (stratum.EndMonths == MAX_MONTHS_BEFORE_NEXT_YEAR)
                        {
                            months = 0;
                            years++;
                        }
                        else
                        {
                            months++;
                        }
                    }
                    else
                    {
                        if (stratum.StartMonths == 0 && stratum.EndMonths == 0)
                        {
                            stratumId = stratum.StratumId;
                            break;
                        }

                        if (stratum.EndMonths > 0)
                        {
                            continue;
                        }
                    }
                }
                else
                {
                    continue;
                }
            }

            return(stratumId);
        }
示例#26
0
        public ActionResult Create([Bind(Include = "Id,DateTimeName")] DateTimeSpan dateTimeSpan)
        {
            if (ModelState.IsValid)
            {
                db.DateTimeSpans.Add(dateTimeSpan);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(dateTimeSpan));
        }
示例#27
0
        public void ReturnsEmptySetWhenNoCampsitesAvailable(int startDate, int endDate, int gap)
        {
            // Setup
            var targetSpan = new DateTimeSpan(new DateTime(startDate.Days().Ticks), new DateTime(endDate.Days().Ticks));

            // Test
            var campsiteIds = service.GetAvailableCampsites(targetSpan, gap).Select(c => c.Id);

            // Assert
            Assert.Empty(campsiteIds);
        }
示例#28
0
        public void CanGetAvailableCampsites(int startDate, int endDate, int idToReturn)
        {
            // Setup
            var targetSpan = new DateTimeSpan(new DateTime(startDate.Days().Ticks), new DateTime(endDate.Days().Ticks));

            // Test
            var campsiteIds = service.GetAvailableCampsites(targetSpan, 1).Select(c => c.Id);

            // Assert
            Assert.Contains(idToReturn, campsiteIds);
        }
示例#29
0
 string OrdinalDay(DateTimeSpan offset)
 {
     if (offset == null)
     {
         return("");
     }
     if (offset.Type != DateTimeSpanTypes.Days)
     {
         return(offset.ToString());
     }
     return(offset.Days.ToString() + "-й день");
 }
示例#30
0
        public void DateTimeYears()
        {
            //Arrange
            DateTime dt1 = new DateTime(2000, 1, 1);
            DateTime dt2 = new DateTime(2001, 1, 1);

            // Act
            var dts = DateTimeSpan.CompareDates(dt1, dt2).Years;

            // Assert
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(dts, 1);
        }
示例#31
0
    public static DateTimeSpan CompareDates(DateTime date1, DateTime date2)
    {
        if (date2 < date1)
        {
            var sub = date1;
            date1 = date2;
            date2 = sub;
        }

        DateTime current = date1;
        int years = 0;
        int months = 0;
        int days = 0;

        Phase phase = Phase.Years;
        DateTimeSpan span = new DateTimeSpan();

        while (phase != Phase.Done)
        {
            switch (phase)
            {
                case Phase.Years:
                    if (current.AddYears(years + 1) > date2)
                    {
                        phase = Phase.Months;
                        current = current.AddYears(years);
                    }
                    else
                    {
                        years++;
                    }
                    break;
                case Phase.Months:
                    if (current.AddMonths(months + 1) > date2)
                    {
                        phase = Phase.Days;
                        current = current.AddMonths(months);
                    }
                    else
                    {
                        months++;
                    }
                    break;
                case Phase.Days:
                    if (current.AddDays(days + 1) > date2)
                    {
                        current = current.AddDays(days);
                        var timespan = date2 - current;
                        span = new DateTimeSpan(years, months, days, timespan.Hours, timespan.Minutes, timespan.Seconds, timespan.Milliseconds);
                        phase = Phase.Done;
                    }
                    else
                    {
                        days++;
                    }
                    break;
            }
        }

        return span;
    }