示例#1
0
        private static decimal GetDaysForThirty360(
            LocalDate startDate,
            LocalDate endDate
            )
        {
            var months =
                Period.Between(startDate, endDate, PeriodUnits.Months).Months;
            var startPlusMonths = startDate.PlusMonths(months);
            var days            =
                Period.Between(startPlusMonths, endDate, PeriodUnits.Days).Days;
            var retVal = months * 30 + (days > 30 ? 30 : days);

            return(retVal);
        }
示例#2
0
        /// <summary>
        ///     Calculates the patients month age at sampling
        /// </summary>
        /// <returns>Age of patient at sampling if sampling date is known, age at receiving date otherwise</returns>
        public static int PatientMonthAgeAtSampling <TSending, TPatient>(this ISendingReference <TSending, TPatient> isolate)
            where TPatient : PatientBase
            where TSending : SendingBase <TPatient>
        {
            var monthAgeAtSampling = 0;

            if (isolate.Sending.Patient.BirthDate.HasValue)
            {
                var birthday = LocalDate.FromDateTime(isolate.Sending.Patient.BirthDate.Value);
                var samplingOrReceivingDate = LocalDate.FromDateTime(isolate.Sending.SamplingDate ?? isolate.Sending.ReceivingDate);
                monthAgeAtSampling = Period.Between(birthday, samplingOrReceivingDate, PeriodUnits.Months).Months;
            }
            return(monthAgeAtSampling);
        }
示例#3
0
        public void Between_LocalDateTimes()
        {
            Period period = Snippet.For(Period.Between(
                                            new LocalDateTime(2015, 1, 23, 21, 30, 15),
                                            new LocalDateTime(2017, 10, 15, 21, 02, 17)));

            Assert.AreEqual(2, period.Years);
            Assert.AreEqual(8, period.Months);
            Assert.AreEqual(21, period.Days);
            Assert.AreEqual(23, period.Hours);
            Assert.AreEqual(32, period.Minutes);
            Assert.AreEqual(2, period.Seconds);
            Assert.AreEqual("P2Y8M21DT23H32M2S", period.ToString());
        }
示例#4
0
        public static List <ForecastHourly> GetHourlyWeatherOverPeriod(SimpleTime start, SimpleTime end, double lat, double lng)
        {
            LocalDateTime begin  = new LocalDateTime(start.Year, start.Month, start.Day, 0, 0);
            LocalDateTime stop   = new LocalDateTime(end.Year, end.Month, end.Day, 0, 0);
            Period        period = Period.Between(begin, stop, PeriodUnits.Days);

            List <ForecastHourly> hourlyData = new List <ForecastHourly>();

            for (int i = 0; i <= period.Days; i++)
            {
                LocalDateTime localtime = begin.PlusDays(i);

                string       timezone = "America/Toronto";
                DateTimeZone tz       = DateTimeZoneProviders.Tzdb[timezone];

                ZonedDateTime zt        = tz.AtLeniently(localtime);
                var           tz_offset = zt.ToDateTimeOffset();

                Task.Run(async() =>
                {
                    var client      = new ForecastApi(API_KEY);
                    Forecast result = await client.GetTimeMachineWeatherAsync(lat, lng, tz_offset);
                    var hourly      = result.Hourly.Hours;
                    for (int h = 0; h < hourly.Count(); h++)
                    {
                        ForecastHourly store_hourly      = new ForecastHourly();
                        store_hourly.ApparentTemperature = hourly[h].ApparentTemperature;
                        store_hourly.CloudCover          = hourly[h].CloudCover;
                        store_hourly.DewPoint            = hourly[h].DewPoint;
                        store_hourly.Humidity            = hourly[h].Humidity;
                        store_hourly.Icon  = hourly[h].Icon;
                        store_hourly.Ozone = hourly[h].Ozone;
                        store_hourly.PrecipitationIntensity   = hourly[h].PrecipitationIntensity;
                        store_hourly.PrecipitationProbability = hourly[h].PrecipitationProbability;
                        store_hourly.Pressure    = hourly[h].Pressure;
                        store_hourly.Summary     = hourly[h].Summary;
                        store_hourly.Temperature = hourly[h].Temperature;
                        store_hourly.Time        = hourly[h].Time;
                        //Instant instant = Instant.FromDateTimeUtc(hourly[h].Time.UtcDateTime); //don't need this, already defined above
                        store_hourly.LocalTime   = zt.LocalDateTime;
                        store_hourly.Visibility  = hourly[h].Visibility;
                        store_hourly.WindBearing = hourly[h].WindBearing;
                        store_hourly.WindSpeed   = hourly[h].WindSpeed;
                        hourlyData.Add(store_hourly);
                    }
                }).Wait();
            }
            return(hourlyData);
        }
示例#5
0
        public static bool IsPastDate(this DateTime compareDate, string callingMethod)
        {
            var localNow      = DateTimeWrapper.NowUtc.Date.ToLocalDateTime();
            var localCompare  = compareDate.ToLocalDateTime();
            var compareDiff   = (compareDate.Date - DateTimeWrapper.NowUtc.Date).TotalDays;
            var comparePeriod = Period.Between(localNow, localCompare, PeriodUnits.Days);

            LogHelper.LogDebugDetails(callingMethod, $"Compare Date: {localCompare}", $"Compare ToUser: {compareDate.ToUser().Date}",
                                      $"Now (UTC): {DateTimeWrapper.NowUtc.Date}",
                                      $"Start Kind: {compareDate.Kind.ToString()}",
                                      $"Now Kind:  {DateTimeWrapper.NowUtc.Kind.ToString()}",
                                      $"Start Period: {comparePeriod.Days}");

            return(comparePeriod.Days < 0);
        }
示例#6
0
        private IEnumerable <LocalTimeInterval> GetDayPattern(LocalDate date)
        {
            if (date < Start)
            {
                return(new LocalTimeInterval[0]);
            }
            if (End.HasValue && date >= End)
            {
                return(new LocalTimeInterval[0]);
            }

            var index = Period.Between(Start, date, PeriodUnits.Days).Days;

            return(Shifts[(int)index % Shifts.Count]);
        }
示例#7
0
        public int GetAlder(int brugerID)
        {
            using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("Dating")))
            {
                LocalDate Fødselsdato = connection.Query <LocalDate>("Bruger_GetAlder @BrugerID", new { BrugerID = brugerID }).Single();

                //DateTimeZone zone = DateTimeZoneProviders.Tzdb["Europe/Copenhagen"];
                //ZonedClock clock = SystemClock.Instance.InZone(zone);
                //int Alder = Period.Between(Fødselsdato, clock.GetCurrentLocalDateTime().Date).Years;

                int Alder = Period.Between(Fødselsdato, SystemClock.Instance.InZone(DateTimeZoneProviders.Tzdb["Europe/Copenhagen"]).GetCurrentLocalDateTime().Date).Years;

                return(Alder);
            }
        }
示例#8
0
        /// <summary>
        /// Creates schemas container.
        /// </summary>
        /// <returns>Initialized <see cref="Schema"/> instance.</returns>
        public Schemas CreateSchemas()
        {
            IDateTimeZoneProvider dateTimeZoneProvider = _settings.DateTimeZoneProvider ?? DateTimeZoneProviders.Tzdb;
            var dateTimeZone  = dateTimeZoneProvider.GetSystemDefault();
            var instant       = Instant.FromDateTimeUtc(DateTime.UtcNow);
            var zonedDateTime = instant.InZone(dateTimeZone);
            var interval      = new Interval(instant,
                                             instant.PlusTicks(TimeSpan.TicksPerDay)
                                             .PlusTicks(TimeSpan.TicksPerHour)
                                             .PlusTicks(TimeSpan.TicksPerMinute)
                                             .PlusTicks(TimeSpan.TicksPerSecond)
                                             .PlusTicks(TimeSpan.TicksPerMillisecond));
            var    dateInterval = new DateInterval(zonedDateTime.Date, zonedDateTime.Date.PlusDays(1));
            Period period       = Period.Between(zonedDateTime.LocalDateTime, interval.End.InZone(dateTimeZone).LocalDateTime, PeriodUnits.AllUnits);

            // https://xml2rfc.tools.ietf.org/public/rfc/html/rfc3339.html#anchor14
            return(new Schemas
            {
                Instant = () => StringSchema(instant, "date-time"),
                LocalDate = () => StringSchema(zonedDateTime.Date, "full-date"),
                LocalTime = () => StringSchema(zonedDateTime.TimeOfDay, "partial-time"),
                LocalDateTime = () => StringSchema(zonedDateTime.LocalDateTime),
                OffsetDateTime = () => StringSchema(instant.WithOffset(zonedDateTime.Offset), "date-time"),
                ZonedDateTime = () => StringSchema(zonedDateTime),
                Interval = () => new OpenApiSchema
                {
                    Type = "object",
                    Properties = new Dictionary <string, OpenApiSchema>
                    {
                        { ResolvePropertyName(nameof(Interval.Start)), StringSchema(interval.Start, "date-time") },
                        { ResolvePropertyName(nameof(Interval.End)), StringSchema(interval.End, "date-time") },
                    },
                },
                DateInterval = () => new OpenApiSchema
                {
                    Type = "object",
                    Properties = new Dictionary <string, OpenApiSchema>
                    {
                        { ResolvePropertyName(nameof(DateInterval.Start)), StringSchema(dateInterval.Start, "full-date") },
                        { ResolvePropertyName(nameof(DateInterval.End)), StringSchema(dateInterval.End, "full-date") },
                    },
                },
                Offset = () => StringSchema(zonedDateTime.Offset, "time-numoffset"),
                Period = () => StringSchema(period),
                Duration = () => StringSchema(interval.Duration),
                DateTimeZone = () => StringSchema(dateTimeZone),
            });
        }
示例#9
0
        private static Dictionary <VoucherRecord, VoucherRecord> MatchVoucherTypes(IEnumerable <VoucherRecord> vouchersA, IEnumerable <VoucherRecord> matchWithTheseB, bool ignoreCompanyName)
        {
            var matchWithTheseListB = matchWithTheseB.ToList();
            var vouchersListA       = vouchersA.ToList();

            bool GetDateInRange(int days, int minInc, int maxEx) => days >= minInc && days < maxEx;

            var dateMatchPasses = new List <Func <LocalDate, LocalDate, bool> >
            {
                (voucherA, voucherB) => voucherA == voucherB,
                (voucherA, voucherB) => GetDateInRange(Period.Between(voucherA, voucherB, PeriodUnits.Days).Days, 0, 3),
                (voucherA, voucherB) => GetDateInRange(Period.Between(voucherA, voucherB, PeriodUnits.Days).Days, 0, 21),
                (voucherA, voucherB) => GetDateInRange(Period.Between(voucherA, voucherB, PeriodUnits.Days).Days, 0, 51),
            };

            if (!ignoreCompanyName)
            {
                dateMatchPasses.Add(
                    (voucherA, voucherB) => GetDateInRange(Period.Between(voucherA, voucherB, PeriodUnits.Days).Days, 0, 91)
                    );
            }

            var result = new Dictionary <VoucherRecord, VoucherRecord>();

            foreach (var dateMatch in dateMatchPasses)
            {
                var matches = vouchersListA.Select(vA =>
                {
                    //if (ignoreCompanyName && vA.GetTransactionsMaxAmount() == 281)
                    //{ }

                    var lb_t24400 = vA.Transactions.First(t => t.AccountId == 24400);
                    var foundLrs  = matchWithTheseListB.Where(vB => dateMatch(vA.Date, vB.Date)).Where(l =>
                    {
                        var lr_t24400 = l.Transactions.First(t => t.AccountId == 24400);
                        return(lr_t24400.Amount == -lb_t24400.Amount &&
                               (ignoreCompanyName ? true : lr_t24400.CompanyName == lb_t24400.CompanyName));
                    });
                    return(new { A = vA, Bs = foundLrs.ToList() });
                });
                var goodMatches = matches.Where(o => o.Bs.Count() == 1).Select(o => (o.A, o.Bs.First())).ToList();
                matchWithTheseListB = matchWithTheseListB.Except(goodMatches.Select(o => o.Item2)).ToList();
                vouchersListA       = vouchersListA.Except(goodMatches.Select(o => o.A)).ToList();

                goodMatches.ForEach(o => result.Add(o.A, o.Item2));
            }
            return(result);
        }
示例#10
0
        private void InitializeCounter()
        {
            int monthCounter = GetMonthAfterBirth();

            var       now       = DateTime.Now;
            LocalDate birthDate = new LocalDate(2019, 8, 12);
            LocalDate today     = new LocalDate(now.Year, now.Month, now.Day);
            Period    age       = Period.Between(birthDate, today);

            TimeElapsed.Text = $"{age.Years} years {age.Months} months {age.Days} days";

            for (var month = 0; month < monthCounter; month++)
            {
                AddGridImage(month);
            }
        }
示例#11
0
        } = 0.667;                                                   // Extra 40 minutes accumulated per year there

        public static double GetVacationHours(DateTime startDate, DateTime endDate, double daysOff = 0)
        {
            // Get number of months total
            if (startDate > endDate)
            {
                return(0);
            }
            int months = MonthDiff(startDate, endDate);

            // Get number of years after start date for extra time
            LocalDate start = new(startDate.Year, startDate.Month, startDate.Day);
            LocalDate end   = new(endDate.Year, endDate.Month, endDate.Day);
            int       years = Period.Between(start, end).Years;

            return((months * ((years * ExtraVacationPerYear) + MonthlyVacation)) - (daysOff * 8));
        }
示例#12
0
        public static string GetTimeBetween(DateTime startTime, DateTime endTime, PeriodUnits pu, bool label)
        {
            // https://nodatime.org/2.4.x/userguide/rationale

            LocalDateTime start  = new LocalDateTime(startTime.Year, startTime.Month, startTime.Day, startTime.Hour, startTime.Minute, startTime.Second);
            LocalDateTime end    = new LocalDateTime(endTime.Year, endTime.Month, endTime.Day, endTime.Hour, endTime.Minute, endTime.Second);
            Period        period = Period.Between(start, end, pu);

            string s = string.Empty;

            if ((pu & PeriodUnits.Years) != 0)
            {
                s = s + string.Format("{0}{1}{2}", string.IsNullOrEmpty(s) ? "" : " ", period.Years, label ? " Years" : "");
            }

            if ((pu & PeriodUnits.Months) != 0)
            {
                s = s + string.Format("{0}{1}{2}", string.IsNullOrEmpty(s) ? "" : " ", period.Months, label ? " Months" : "");
            }

            if ((pu & PeriodUnits.Weeks) != 0)
            {
                s = s + string.Format("{0}{1}{2}", string.IsNullOrEmpty(s) ? "" : " ", period.Weeks, label ? " Weeks" : "");
            }

            if ((pu & PeriodUnits.Days) != 0)
            {
                s = s + string.Format("{0}{1}{2}", string.IsNullOrEmpty(s) ? "" : " ", period.Days, label ? " Days" : "");
            }

            if ((pu & PeriodUnits.Hours) != 0)
            {
                s = s + string.Format("{0}{1}{2}", string.IsNullOrEmpty(s) ? "" : " ", period.Hours, label ? " Hours" : "");
            }

            if ((pu & PeriodUnits.Minutes) != 0)
            {
                s = s + string.Format("{0}{1}{2}", string.IsNullOrEmpty(s) ? "" : " ", period.Minutes, label ? " Minutes" : "");
            }

            if ((pu & PeriodUnits.Seconds) != 0)
            {
                s = s + string.Format("{0}{1}{2}", string.IsNullOrEmpty(s) ? "" : " ", period.Seconds, label ? " Seconds" : "");
            }

            return(s);
        }
示例#13
0
        static void Main(string[] args)
        {
            //This is an attempt to make a birthday checker
            //User will enter DOB, program will compare that to current day
            //If the DOB indicates the person is 21 or, program will display VALID SALE
            //This is a test of concept
            //I just want to see if I can do it

            Console.Write("Enter DOB: ");
            string input = Console.ReadLine();                                                        //get input
            LocalDateTimePattern pattern = LocalDateTimePattern.CreateWithInvariantCulture("MMddyy"); //set pattern for parsing from string

            ParseResult <LocalDateTime> parseResult = pattern.Parse(input);                           //parse string from input

            LocalDateTime dob = parseResult.Value;                                                    //returns value of parse result

            //date of birth set as variable 'dob'

            Instant today = SystemClock.Instance.Now;                //gets current date from system clock

            var timeZone = DateTimeZoneProviders.Tzdb["US/Central"]; //gets US Central as Time zone

            ZonedDateTime zonedToday = today.InZone(timeZone);       //converts instant variable to ZonedDateTime in Central Time

            LocalDateTime localToday = zonedToday.LocalDateTime;     //Converts ZonedDateTime to LocalDateTime, suitable for Period

            //final, useable value for today set as variable 'localToday'

            Period agePeriod = Period.Between(dob, localToday); //gets amount of time between two dates

            long age = agePeriod.Years;                         //gets years component of period. Component Years takes long data type

            //this is the variable to use for age. We don't care about months, weeks, days, etc

            //Only LocalDateTime variables can use Period. Instant variable must be converted to LocalDateTime via ZonedDateTime

            if (age >= 21) //simple conditional. Does the date of birth put the person at or over 21 years old
            {
                Console.WriteLine($"VALID SALE ({age})");
            }
            else
            {
                Console.WriteLine($"DENY SALE({age})");
            }

            //I can do it
        }
示例#14
0
        public void BetweenYearMonth_SingleUnit(string startText, string endText, PeriodUnits units, int expectedValue)
        {
            var start = YearMonthPattern.Iso.Parse(startText).Value;
            var end = YearMonthPattern.Iso.Parse(endText).Value;
            var forward = Period.Between(start, end, units);
            var expectedForward = new PeriodBuilder {
                [units] = expectedValue
            }.Build();

            Assert.AreEqual(expectedForward, forward);
            var backward = Period.Between(end, start, units);
            var expectedBackward = new PeriodBuilder {
                [units] = -expectedValue
            }.Build();

            Assert.AreEqual(expectedBackward, backward);
        }
示例#15
0
        // This is legacy support for PostgreSQL's old floating-point timestamp encoding - finally removed in PG 10 and not used for a long
        // time. Unfortunately CrateDB seems to use this for some reason.
        internal static void WriteDouble(Instant instant, NpgsqlWriteBuffer buf)
        {
            var localDateTime     = instant.InUtc().LocalDateTime;
            var totalDaysSinceEra = Period.Between(default(LocalDateTime), localDateTime, PeriodUnits.Days).Days;
            var secondOfDay       = localDateTime.NanosecondOfDay / 1000000000d;

            if (totalDaysSinceEra >= 730119)
            {
                var uSecsDate = (totalDaysSinceEra - 730119) * 86400d;
                buf.WriteDouble(uSecsDate + secondOfDay);
            }
            else
            {
                var uSecsDate = (730119 - totalDaysSinceEra) * 86400d;
                buf.WriteDouble(-(uSecsDate - secondOfDay));
            }
        }
示例#16
0
        public void LeapYear()
        {
            //given
            var policy = new PolicyVersion
            {
                PolicyId   = 1,
                PolicyFrom = new DateTime(2020, 2, 29),
                PolicyTo   = new DateTime(2020, 2, 29).AddYears(1).AddDays(-1)
            };

            var serviceDate = new DateTime(2020, 5, 1);

            //when
            var limitPeriod = new PolicyYearLimitPeriod().Calculate(serviceDate, policy);

            //then
            Assert.Equal(Period.Between(new DateTime(2020, 2, 29), new DateTime(2021, 2, 27)), limitPeriod);
        }
示例#17
0
        public void ServiceDateInsideFirstPolicyYear_PeriodStartEqualToPolicyStart_PeriodEndsYearAfterThat()
        {
            //given
            var policy = new PolicyVersion
            {
                PolicyId   = 1,
                PolicyFrom = new DateTime(2019, 1, 1),
                PolicyTo   = new DateTime(2019, 12, 31)
            };

            var serviceDate = new DateTime(2019, 5, 1);

            //when
            var limitPeriod = new PolicyYearLimitPeriod().Calculate(serviceDate, policy);

            //then
            Assert.Equal(Period.Between(new DateTime(2019, 1, 1), new DateTime(2019, 12, 31)), limitPeriod);
        }
示例#18
0
        public static double GetFutureVacationHorusFromCurrentVacationTime(DateTime startDate, DateTime endDate, double currentVacation, double daysOff = 0)
        {
            // Get number of months total
            if (startDate > endDate)
            {
                return(0);
            }
            int months = MonthDiff(DateTime.Now, endDate);

            // Get number of years after start date for extra time
            LocalDate start = new(startDate.Year, startDate.Month, startDate.Day);
            LocalDate end   = new(endDate.Year, endDate.Month, endDate.Day);
            int       years = Period.Between(start, end).Years;

            double futureTime = (months * ((years * ExtraVacationPerYear) + MonthlyVacation)) + currentVacation;

            return(futureTime - (daysOff * 8));
        }
示例#19
0
        private async Task UpdateChannelTopic(DateTime utcNow)
        {
            try
            {
                await LoggingService.LogDebugAsync($"{nameof(UpdateChannelTopic)} started", nameof(TimerService)).ConfigureAwait(false);

                if (_client.GetChannel(Convert.ToUInt64(_config["channelTopic:channelId"])) is not SocketTextChannel chan)
                {
                    return;
                }

                if (!DateTime.TryParse(_config["channelTopic:date"], out var date))
                {
                    return;
                }

                var localDate = LocalDate.FromDateTime(date);

                var eta = Period.Between(localDate, utcNow.UtcToPragueZonedDateTime().Date, PeriodUnits.Days).Days;
                if (eta == CacheService.TimerService_ChannelTopicEta)
                {
                    return;
                }

                CacheService.TimerService_ChannelTopicEta = eta;

                var text = _config["channelTopic:text"];

                if (string.IsNullOrEmpty(text))
                {
                    return;
                }

                text = Helpers.ReplaceEmotesInText(text).Replace("{eta}", (eta > 0 ? "+" : "") + eta);

                await LoggingService.LogInfoAsync($"Updating {chan} topic to '{text}'", nameof(TimerService)).ConfigureAwait(false);

                await chan.ModifyAsync(ch => ch.Topic = text).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                await LoggingService.LogExceptionAsync(ex, nameof(TimerService), $"{nameof(UpdateChannelTopic)} failed").ConfigureAwait(false);
            }
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var date      = LocalDateTime.FromDateTime((DateTime)value);
            var timeSince = Period.Between(date, LocalDateTime.FromDateTime(DateTime.Now));
            var days      = timeSince.Days;
            var hours     = timeSince.Hours;
            var min       = timeSince.Minutes;

            string tense = "have passed.";

            if (timeSince.Ticks < 0)
            {
                tense = "until.";
            }

            string yearsString = "";

            if (timeSince.Years != 0)
            {
                yearsString = $"{Math.Abs(timeSince.Years)} years, ";
            }

            string monthsString = "";

            if (timeSince.Months != 0)
            {
                monthsString = $"{Math.Abs(timeSince.Months)} months, ";
            }
            string daysString = "";

            if (days != 0)
            {
                daysString = $"{Math.Abs(days)} days, ";
            }
            string hoursString = "";

            if (hours != 0)
            {
                hoursString = $"{Math.Abs(hours)} hours, ";
            }

            return($"{yearsString}{monthsString}{daysString}{hoursString}{Math.Abs(min)} minutes {tense}");;
        }
示例#21
0
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       EmployeeRequirementsLogic requirement)
        {
            var emplomentCommenced = context.User
                                     .FindFirst(claim => claim.Type == CustomClaimTypes.EmploymentCommenced).Value;

            var employmentStarted = Convert.ToDateTime(emplomentCommenced);
            var today             = LocalDate.FromDateTime(DateTime.Now);

            var monthsPassed = Period
                               .Between(employmentStarted.ToLocalDateTime(), today.AtMidnight()).Months;

            if (monthsPassed >= requirement.MinimumMonthsEmployed)
            {
                context.Succeed(requirement);
            }

            return(Task.CompletedTask);
        }
示例#22
0
        public void BetweenLocalDateTimes_NotInt64Representable()
        {
            LocalDateTime start = new LocalDateTime(-5000, 1, 1, 0, 1, 2, 123);
            LocalDateTime end   = new LocalDateTime(9000, 1, 1, 1, 2, 3, 456);

            Assert.False((end.ToLocalInstant().TimeSinceLocalEpoch - start.ToLocalInstant().TimeSinceLocalEpoch).IsInt64Representable);

            Period expected = new PeriodBuilder
            {
                // 365.2425 * 14000 = 5113395
                Hours        = 5113395L * 24 + 1,
                Minutes      = 1,
                Seconds      = 1,
                Milliseconds = 333
            }.Build();
            Period actual = Period.Between(start, end, PeriodUnits.AllTimeUnits);

            Assert.AreEqual(expected, actual);
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var eventModel = (Event)value;

            if (eventModel == null || eventModel.EventEndDate == DateTime.MinValue || eventModel.EventDate > DateTime.Now)
            {
                return(null);
            }
            var           tenseString = string.Empty;
            LocalDateTime endDate;

            if (DateTime.Now < eventModel.EventEndDate)
            {
                endDate     = LocalDateTime.FromDateTime(DateTime.Now);
                tenseString = " so far";
            }
            else
            {
                endDate = LocalDateTime.FromDateTime(eventModel.EventEndDate);
            }
            var    timeSpanned       = Period.Between(LocalDateTime.FromDateTime(eventModel.EventDate), endDate);
            string timeSpannedString = $"{timeSpanned.Minutes} minutes";

            if (timeSpanned.Hours > 0)
            {
                timeSpannedString = timeSpannedString.Insert(0, $"{timeSpanned.Hours} hours, ");
            }

            if (timeSpanned.Days > 0)
            {
                timeSpannedString = timeSpannedString.Insert(0, $"{timeSpanned.Days} days, ");
            }
            if (timeSpanned.Months > 0)
            {
                timeSpannedString = timeSpannedString.Insert(0, $"{timeSpanned.Months} months, ");
            }
            if (timeSpanned.Years > 0)
            {
                timeSpannedString = timeSpannedString.Insert(0, $"{timeSpanned.Years} years, ");
            }

            return($"Lasted {timeSpannedString}{tenseString}.");
        }
示例#24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SchemaExamples"/> class.
        /// Creates example value by provided <see cref="DateTime"/> and <see cref="IDateTimeZoneProvider"/>.
        /// </summary>
        /// <param name="dateTimeZoneProvider">IDateTimeZoneProvider instance.</param>
        /// <param name="dateTimeUtc"><see cref="DateTime"/>. If not set then <see cref="DateTime.UtcNow"/> will be used.</param>
        /// <param name="dateTimeZone">Optional DateTimeZone name. If not set SystemDefault will be used.</param>
        public SchemaExamples(
            IDateTimeZoneProvider dateTimeZoneProvider,
            DateTime?dateTimeUtc = null,
            string?dateTimeZone  = null)
        {
            DateTime dateTimeUtcValue = dateTimeUtc ?? DateTime.UtcNow;

            if (dateTimeUtcValue.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException("dateTimeUtc should be UTC", nameof(dateTimeUtc));
            }

            if (dateTimeZone != null)
            {
                DateTimeZone = dateTimeZoneProvider.GetZoneOrNull(dateTimeZone) ?? dateTimeZoneProvider.GetSystemDefault();
            }
            else
            {
                DateTimeZone = dateTimeZoneProvider.GetSystemDefault();
            }

            Instant = Instant.FromDateTimeUtc(dateTimeUtcValue);

            ZonedDateTime = Instant.InZone(DateTimeZone);

            Interval = new Interval(Instant,
                                    Instant.PlusTicks(TimeSpan.TicksPerDay)
                                    .PlusTicks(TimeSpan.TicksPerHour)
                                    .PlusTicks(TimeSpan.TicksPerMinute)
                                    .PlusTicks(TimeSpan.TicksPerSecond)
                                    .PlusTicks(TimeSpan.TicksPerMillisecond));

            DateInterval = new DateInterval(ZonedDateTime.Date, ZonedDateTime.Date.PlusDays(1));

            Period = Period.Between(ZonedDateTime.LocalDateTime, Interval.End.InZone(DateTimeZone).LocalDateTime, PeriodUnits.AllUnits);

            OffsetDate = new OffsetDate(ZonedDateTime.Date, ZonedDateTime.Offset);

            OffsetTime = new OffsetTime(ZonedDateTime.TimeOfDay, ZonedDateTime.Offset);

            OffsetDateTime = Instant.WithOffset(ZonedDateTime.Offset);
        }
示例#25
0
        public override void Write(LocalDate value, NpgsqlWriteBuffer buf, NpgsqlParameter parameter)
        {
            if (_convertInfinityDateTime)
            {
                if (value == LocalDate.MaxIsoValue)
                {
                    buf.WriteInt32(int.MaxValue);
                    return;
                }
                if (value == LocalDate.MinIsoValue)
                {
                    buf.WriteInt32(int.MinValue);
                    return;
                }
            }

            var totalDaysSinceEra = Period.Between(default(LocalDate), value, PeriodUnits.Days).Days;

            buf.WriteInt32(totalDaysSinceEra - 730119);
        }
示例#26
0
        public void HasDateComponent_Compound()
        {
            LocalDateTime dt1 = new LocalDateTime(2000, 1, 1, 10, 45, 00);
            LocalDateTime dt2 = new LocalDateTime(2000, 2, 4, 11, 50, 00);

            // Case 1: Entire period is time-based (no date units available)
            Assert.IsFalse(Period.Between(dt1.TimeOfDay, dt2.TimeOfDay).HasDateComponent);

            // Case 2: Period contains date and time units, but date units are all zero
            Assert.IsFalse(Period.Between(dt1, dt1.Date + dt2.TimeOfDay).HasDateComponent);

            // Case 3: Entire period is date-based, but 0. (Same local date twice here.)
            Assert.IsFalse(Period.Between(dt1.Date, dt1.Date).HasDateComponent);

            // Case 4: Period contains date and time units, and some date units are non-zero
            Assert.IsTrue(Period.Between(dt1, dt2).HasDateComponent);

            // Case 5: Entire period is date-based, and some time units are non-zero
            Assert.IsTrue(Period.Between(dt1.Date, dt2.Date).HasDateComponent);
        }
示例#27
0
        public void BetweenLocalDateTimes_OnLeapYearIslamic()
        {
            var calendar = CalendarSystem.GetIslamicCalendar(IslamicLeapYearPattern.Base15, IslamicEpoch.Civil);

            Assert.IsTrue(calendar.IsLeapYear(2));
            Assert.IsFalse(calendar.IsLeapYear(3));

            LocalDateTime dt1 = new LocalDateTime(2, 12, 30, 2, 0, calendar);
            LocalDateTime dt2 = new LocalDateTime(2, 12, 30, 4, 0, calendar);
            LocalDateTime dt3 = new LocalDateTime(3, 12, 29, 3, 0, calendar);

            // Adding a year truncates to 0003-12-28T02:00:00, then add an hour.
            Assert.AreEqual(Parse("P1YT1H"), Period.Between(dt1, dt3));
            // Adding a year would overshoot. Adding 11 months takes us to month 03-11-30T04:00.
            // Adding another 28 days takes us to 03-12-28T04:00, then add another 23 hours to finish.
            Assert.AreEqual(Parse("P11M28DT23H"), Period.Between(dt2, dt3));

            // Subtracting 11 months takes us to 03-01-29T03:00. Subtracting another 29 days
            // takes us to 02-12-30T03:00, and another hour to get to the target.
            Assert.AreEqual(Parse("P-11M-29DT-1H"), Period.Between(dt3, dt1));
            Assert.AreEqual(Parse("P-11M-28DT-23H"), Period.Between(dt3, dt2));
        }
        void EverySecondTimer_Tick(object sender, EventArgs e)
        {
            RemainingTime = null;
            RTime         = null;

            if (CurrentAlarm != null)
            {
                RemainingTime = Convert.ToDateTime(CurrentAlarm.Time).TimeOfDay - DateTime.Now.TimeOfDay;


                var endTime   = new LocalDateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, CurrentAlarm.Time.Hour, CurrentAlarm.Time.Minute, CurrentAlarm.Time.Second);
                var startTime = new LocalDateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);


                RTime = Period.Between(startTime, endTime,
                                       PeriodUnits.Years | PeriodUnits.Months | PeriodUnits.Days | PeriodUnits.Hours | PeriodUnits.Minutes | PeriodUnits.Seconds);
            }
            else
            {
                if (NextAlarm != null && NextAlarm.Any())
                {
                    var endTime = new LocalDateTime(NextAlarm.First().Value.Year, NextAlarm.First().Value.Month,
                                                    NextAlarm.First().Value.Day, NextAlarm.First().Key.Time.Hour, NextAlarm.First().Key.Time.Minute,
                                                    NextAlarm.First().Key.Time.Second);
                    var startTime = new LocalDateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,
                                                      DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);


                    RTime = Period.Between(startTime, endTime,
                                           PeriodUnits.Years | PeriodUnits.Months | PeriodUnits.Days | PeriodUnits.Hours |
                                           PeriodUnits.Minutes | PeriodUnits.Seconds);
                }
            }


            //if (RemainingTime == null) return;
            //var date = new DateTime(NextPossibleAlarm().First().Value.AddTicks(Convert.ToDateTime(NextPossibleAlarm().First().Key.Time).TimeOfDay.Ticks).Ticks);
            //TimeSpan = string.Format("{0:### Y;-## ; }  {1:### M;-## ; }  {2:### D;-## ; } {3:### H;-## ; }  {4:### M;-## ; } {5:### S;-## ; }", date.Year,date.Month,date.Day,date.Hour,date.Minute,date.Second);
        }
示例#29
0
        private string GetDateAdded(DateTime localDate)
        {
            if (localDate.Date == DateTime.UtcNow.Date)
            {
                return(Manager.TranslationService.GetString("devices-add-date-days", UI.Resources.Localization.TranslationService.Args("numDays", 0)));
            }

            var period = Period.Between(new LocalDate(localDate.Year, localDate.Month, localDate.Day), new LocalDate(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day));

            if (period.Years > 0)
            {
                return(Manager.TranslationService.GetString("devices-add-date-years", UI.Resources.Localization.TranslationService.Args("numYears", period.Years)));
            }
            else if (period.Months > 0)
            {
                return(Manager.TranslationService.GetString("devices-add-date-months", UI.Resources.Localization.TranslationService.Args("numMonths", period.Months)));
            }
            else
            {
                return(Manager.TranslationService.GetString("devices-add-date-days", UI.Resources.Localization.TranslationService.Args("numDays", period.Days)));
            }
        }
        protected override Task HandleRequirementAsync(
            AuthorizationHandlerContext context,
            MinimumMonthsEmployedRequirement requirement)
        {
            var user = context.User;


            var employmentCommenced = user.FindFirst(claim => claim.Type == CustomClaimTypes.EmploymentCommenced).Value;

            var employmentStarted = Convert.ToDateTime(employmentCommenced);
            var today             = LocalDateTime.FromDateTime(DateTime.Now);

            var monthsPassed = Period
                               .Between(new LocalDateTime(employmentStarted.Year, employmentStarted.Month, employmentStarted.Day, employmentStarted.Hour, employmentStarted.Minute, employmentStarted.Second), today, PeriodUnits.Months)
                               .Months;

            if (monthsPassed >= requirement.MinimumMonthsEmployed)
            {
                context.Succeed(requirement);
            }
            return(Task.CompletedTask);
        }