Esempio n. 1
0
    public static DateOnly AddWorkingDays(this DateOnly thisDate, int x, NonWorkingDays?nonWorkingDays = null)
    {
        if (x == 0)
        {
            return(thisDate);
        }
        else if (x > 0)
        {
            var i = 0;
            do
            {
                thisDate = thisDate.AddDays(1).GetNextWorkingDay(nonWorkingDays);
                i++;
            } while (i < x);

            return(thisDate);
        }
        else
        {
            var i = 0;
            do
            {
                thisDate = thisDate.AddDays(-1).GetPreviousWorkingDay(nonWorkingDays);
                i++;
            } while (i < Math.Abs(x));

            return(thisDate);
        }
    }
Esempio n. 2
0
    public void Should_correctly_calculate_other_easter_derived_holidays(int year, DateOnly easterSunday)
    {
        //expected
        var expectedGoodFriday      = easterSunday.AddDays(-2);
        var expectedEasterMonday    = easterSunday.AddDays(1);
        var expectedAscensionOfJayZ = easterSunday.AddDays(39);
        var expectedWhitSunday      = easterSunday.AddDays(49);
        var expectedWhiteMonday     = expectedWhitSunday.AddDays(1);

        //actual
        var goodFriday      = Holidays.GoodFriday(year);
        var easterMonday    = Holidays.EasterMonday(year);
        var ascensionOfJayZ = Holidays.AscensionOfJayZ(year);
        var whitSunday      = Holidays.WhitSunday(year);
        var whitMonday      = Holidays.WhitMonday(year);

        //compare
        var allMatch = expectedGoodFriday == goodFriday &&
                       expectedEasterMonday == easterMonday &&
                       expectedAscensionOfJayZ == ascensionOfJayZ &&
                       expectedWhitSunday == whitSunday &&
                       expectedWhiteMonday == whitMonday;

        Assert.True(allMatch);
    }
        /// <summary>
        /// 获取某日期所在的周的开始日期和结束日期
        /// </summary>
        /// <param name="dtNow">当前日期(年月日)</param>
        /// <returns>开始日期,结束日期</returns>
        public static (DateOnly firstDay, DateOnly lastDay) GetDateWeek(DateOnly dtNow)
        {
            //今天是星期几
            int      iNowOfWeek = (int)dtNow.DayOfWeek;
            DateOnly dtWeekSt   = dtNow.AddDays(0 - iNowOfWeek);
            DateOnly dtWeekEd   = dtNow.AddDays(6 - iNowOfWeek);

            return(dtWeekSt, dtWeekEd);
        }
Esempio n. 4
0
    public void TransformDateInJsPatch()
    {
        using var store = GetDocumentStore();
        var @do    = new DateOnly(2022, 2, 21);
        var to     = new TimeOnly(21, 11, 00);
        var entity = new DateAndTimeOnly()
        {
            DateOnly = @do, TimeOnly = to
        };
        {
            using var session = store.OpenSession();
            session.Store(entity);
            session.SaveChanges();
        }
        var operation = store.Operations.Send(new PatchByQueryOperation(@"
declare function modifyDateInJs(date, days) {
  var result = new Date(date);
  result.setDate(result.getDate() + days);
  return result.toISOString().substring(0,10);
}

from DateAndTimeOnlies update { this.DateOnly = modifyDateInJs(this.DateOnly, 1); }"));

        operation.WaitForCompletion(TimeSpan.FromSeconds(5));
        {
            using var session = store.OpenSession();
            WaitForUserToContinueTheTest(store);
            var result = session.Query <DateAndTimeOnly>().Single();
            Assert.Equal(@do.AddDays(1), result.DateOnly);
        }
    }
        /// <summary>
        /// 获取某年第某周的开始日期和结束日期
        /// </summary>
        /// <param name="year">当前日期(年月日)</param>
        /// <param name="numWeek">第几周</param>
        /// <returns>开始日期,结束日期</returns>
        public static (DateOnly firstDay, DateOnly lastDay) GetDateWeek(int year, int numWeek)
        {
            var dt = new DateOnly(year, 1, 1);

            dt = dt.AddDays((numWeek - 1) * 7);
            return(GetDateWeek(dt));
        }
Esempio n. 6
0
        private static WeekMenu CreateTestWeekMenu(DateOnly date)
        {
            var menu1 = new TodayMenu(date)
            {
                Breakfast = new Menu(MenuType.Breakfast)
                {
                    Menus        = new[] { "aaa", "bbb", "ccc", "dddd" },
                    SpecialMenus = new[] { "aaa", "bbb", "ccc", "dddd" }
                },
                Lunch = new Menu(MenuType.Breakfast)
                {
                    Menus        = new[] { "aaa", "bbb", "ccc", "dddd" },
                    SpecialMenus = new[] { "aaa", "bbb", "ccc", "dddd" }
                },
                Dinner = new Menu(MenuType.Breakfast)
                {
                    Menus        = new[] { "aaa", "bbb", "ccc", "dddd" },
                    SpecialMenus = new[] { "aaa", "bbb", "ccc", "dddd" }
                }
            };

            var menu2 = menu1 with
            {
                Date  = date.AddDays(1),
                Lunch = new Menu(MenuType.Breakfast)
                {
                    Menus = new[] { "aaa", "bbb" }
                }
            };

            return(new WeekMenu(new[] { menu1, menu2 }));
        }
    }
        /// <summary>
        /// 获取某日期所在的月的月初日期和月末日期
        /// </summary>
        /// <param name="dtNow">当前日期</param>
        /// <returns>月初,月末</returns>
        public static (DateOnly firstDay, DateOnly lastDay) GetDateMonth(DateOnly dtNow)
        {
            DateOnly dtFirstDay = dtNow.AddDays(1 - dtNow.Day);        //本月月初
            DateOnly dtLastDay  = dtFirstDay.AddMonths(1).AddDays(-1); //本月月末

            //dtMonthEd = dtMonthSt.AddDays((dtNow.AddMonths(1) - dtNow).Days - 1);  //本月月末
            return(dtFirstDay, dtLastDay);
        }
 public Task <WeatherForecast[]> GetForecastAsync(DateOnly startDate)
 {
     return(Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast
     {
         Date = startDate.AddDays(index),
         TemperatureC = Random.Shared.Next(-20, 55),
         Summary = Summaries[Random.Shared.Next(Summaries.Length)]
     }).ToArray()));
 }
        /// <summary>
        /// 判断两个日期是否是在同一周
        /// </summary>
        /// <param name="date1"></param>
        /// <param name="date2"></param>
        /// <returns></returns>
        public static bool IsWeekSame(String date1, String date2)
        {
            DateOnly dt1    = DateOnly.Parse(date1);
            DateOnly dt2    = DateOnly.Parse(date2);
            DateOnly temp1  = dt1.AddDays(-(int)dt1.DayOfWeek);
            DateOnly temp2  = dt2.AddDays(-(int)dt2.DayOfWeek);
            bool     result = temp1 == temp2;

            return(result);
        }
Esempio n. 10
0
    public static DateOnly GetPreviousWorkingDay(this DateOnly thisDate, NonWorkingDays?nonWorkingDays = null)
    {
        var date = thisDate.AddDays(-1);

        while (!date.IsWorkingDay(nonWorkingDays))
        {
            date = date.AddDays(-1);
        }
        return(date);
    }
Esempio n. 11
0
    public void PatchDateOnlyAndTimeOnly()
    {
        using var store = GetDocumentStore();
        var    @do = new DateOnly(2022, 2, 21);
        var    to  = new TimeOnly(21, 11, 00);
        string id;
        var    entity = new DateAndTimeOnly()
        {
            DateOnly = @do,
            TimeOnly = to
        };
        {
            using var session = store.OpenSession();
            session.Store(entity);
            session.SaveChanges();
            id = session.Advanced.GetDocumentId(entity);
        }

        {
            using var session = store.OpenSession();
            session.Advanced.Patch <DateAndTimeOnly, DateOnly>(id, x => x.DateOnly, @do.AddDays(1));
            session.SaveChanges();
        }

        {
            using var session = store.OpenSession();
            var single = session.Query <DateAndTimeOnly>().Single();
            Assert.Equal(@do.AddDays(1), single.DateOnly);
        }

        {
            using var session = store.OpenSession();
            session.Advanced.Patch <DateAndTimeOnly, TimeOnly>(id, x => x.TimeOnly, to.AddHours(1));
            session.SaveChanges();
        }

        {
            using var session = store.OpenSession();
            var single = session.Query <DateAndTimeOnly>().Single();
            Assert.Equal(to.AddHours(1), single.TimeOnly);
        }
    }
Esempio n. 12
0
        public static void AddDaysTest()
        {
            DateOnly dateOnly = DateOnly.MinValue.AddDays(1);

            Assert.Equal(1, dateOnly.DayNumber);
            dateOnly = dateOnly.AddDays(1);
            Assert.Equal(2, dateOnly.DayNumber);
            dateOnly = dateOnly.AddDays(100);
            Assert.Equal(102, dateOnly.DayNumber);

            dateOnly = DateOnly.MaxValue.AddDays(-1);
            Assert.Equal(DateOnly.MaxValue.DayNumber - 1, dateOnly.DayNumber);
            dateOnly = dateOnly.AddDays(-1);
            Assert.Equal(DateOnly.MaxValue.DayNumber - 2, dateOnly.DayNumber);
            dateOnly = dateOnly.AddDays(-100);
            Assert.Equal(DateOnly.MaxValue.DayNumber - 102, dateOnly.DayNumber);

            Assert.Throws <ArgumentOutOfRangeException>(() => DateOnly.MinValue.AddDays(-1));
            Assert.Throws <ArgumentOutOfRangeException>(() => DateOnly.MaxValue.AddDays(1));
        }
Esempio n. 13
0
    public DateOnly GetPreviousWorkDay(DateOnly day)
    {
        var daysBack  = -1;
        var dayOfWeek = day.DayOfWeek;

        if (dayOfWeek is DayOfWeek.Sunday or DayOfWeek.Monday)
        {
            daysBack -= dayOfWeek == DayOfWeek.Sunday ? 1 : 2;
        }

        return(day.AddDays(daysBack));
    }
Esempio n. 14
0
    public static void CreateDays(DateOnly startDate, DateOnly endDate)
    {
        List <CalendarDayEntity> days = new List <CalendarDayEntity>();

        for (DateOnly d = startDate; d < endDate; d = d.AddDays(1))
        {
            days.Add(new CalendarDayEntity {
                Date = d
            });
        }
        days.BulkInsert();
    }
Esempio n. 15
0
    public void Should_use_saturday_and_sunday_as_default_weekend_definition()
    {
        var saturday  = new DateOnly(2022, 4, 23);
        var sunday    = saturday.AddDays(1);
        var monday    = sunday.AddDays(1);
        var tuesday   = monday.AddDays(1);
        var wednesday = tuesday.AddDays(1);
        var thursday  = wednesday.AddDays(1);
        var friday    = thursday.AddDays(1);

        var defaultWeekendIsSatAndSun = saturday.isWeekend() &&
                                        sunday.isWeekend() &&
                                        !monday.isWeekend() &&
                                        !tuesday.isWeekend() &&
                                        !wednesday.isWeekend() &&
                                        !thursday.isWeekend() &&
                                        !friday.isWeekend();

        Assert.True(defaultWeekendIsSatAndSun);
    }
Esempio n. 16
0
        public async Task <List <DateListItem> > GetDatesFromRange(DateOnly today, bool withEmptyDates)
        {
            var daysCount  = (await _appSettingsService.GetAppSettingInt(AppSettingsKey.ImportantDaysDisplayRange)) ?? throw new Exception("Setting 'ImportantDaysDisplayRange' does not exists");
            var allRecords = await GetAllDates(today);

            var startDate  = today.AddDays(-daysCount);
            var datesRange = Enumerable.Range(0, daysCount * 2)
                             .Select(i => startDate.AddDays(i))
                             .Select(d => new DateListItem(Guid.Empty, d, d, "", "", ""))
                             .ToList();

            var datesFromRange = new List <DateListItem>();
            var emptyDates     = new HashSet <DateListItem>();

            foreach (var rec in allRecords)
            {
                var emptyDate = datesRange.SingleOrDefault(d => d.TransferredDate.Month == rec.TransferredDate.Month && d.TransferredDate.Day == rec.TransferredDate.Day);
                if (emptyDate == null)
                {
                    continue;
                }

                datesFromRange.Add(rec with {
                    TransferredDate = emptyDate.TransferredDate
                });
                if (!emptyDates.Contains(emptyDate))
                {
                    emptyDates.Add(emptyDate);
                }
            }

            if (!withEmptyDates)
            {
                return(datesFromRange.OrderBy(d => d.TransferredDate).ToList());
            }

            datesRange = datesRange.Except(emptyDates).ToList();
            datesRange.AddRange(datesFromRange);

            return(datesRange.OrderBy(d => d.TransferredDate).ToList());
        }
Esempio n. 17
0
    public void Should_respect_deviating_weekend_definition()
    {
        var saturday  = new DateOnly(2022, 4, 23);
        var sunday    = saturday.AddDays(1);
        var monday    = sunday.AddDays(1);
        var tuesday   = monday.AddDays(1);
        var wednesday = tuesday.AddDays(1);
        var thursday  = wednesday.AddDays(1);
        var friday    = thursday.AddDays(1);

        //weekend is WED + FRI
        var nwd = new NonWorkingDays {
            Weekend = new List <DayOfWeek> {
                DayOfWeek.Wednesday, DayOfWeek.Friday
            }
        };
        var customWeekendIsWedAndFri = !saturday.isWeekend(nwd) &&
                                       !sunday.isWeekend(nwd) &&
                                       !monday.isWeekend(nwd) &&
                                       !tuesday.isWeekend(nwd) &&
                                       wednesday.isWeekend(nwd) &&
                                       !thursday.isWeekend(nwd) &&
                                       friday.isWeekend(nwd);

        //there is no weekend
        var nwd2 = new NonWorkingDays {
            Weekend = new List <DayOfWeek>()
        };
        var thereIsNoWeekend = !saturday.isWeekend(nwd2) &&
                               !sunday.isWeekend(nwd2) &&
                               !monday.isWeekend(nwd2) &&
                               !tuesday.isWeekend(nwd2) &&
                               !wednesday.isWeekend(nwd2) &&
                               !thursday.isWeekend(nwd2) &&
                               !friday.isWeekend(nwd2);

        Assert.True(customWeekendIsWedAndFri && thereIsNoWeekend);
    }
Esempio n. 18
0
 /// <summary>
 /// 10 days from the provided date
 /// </summary>
 public static DateOnly DaysFrom(DateOnly date)
 {
     return(date.AddDays(10));
 }
Esempio n. 19
0
        // This will look for payments between the two dates but also transfers up to 5 days before the toDate and
        // 5 days before the fromDate
        private async Task <List <VenmoTransaction> > GetVenmoTransactionsBetweenDates(DateOnly fromDate, DateOnly toDate, VenmoApi venmoApi, Database.Models.VenmoUser venmoUser)
        {
            logger.LogDebug($"Finding Venmo transactions between {fromDate} and {toDate}");
            List <VenmoTransaction> transactions  = new List <VenmoTransaction>();
            string?          beforeId             = null;
            bool             foundAllTransactions = false;
            VenmoTransaction?toTransfer           = null;
            VenmoTransaction?fromTransfer         = null;
            VenmoTransaction?previousTransaction  = null;

            do
            {
                var transactionsResponse = await venmoApi.GetTransactions(beforeId);

                if (transactionsResponse.Data != null)
                {
                    foreach (var transaction in transactionsResponse.Data)
                    {
                        if (transaction.DateCreated != null && transaction.Type != null)
                        {
                            if (transaction.Type == "transfer")
                            {
                                DateTime transactionDate = DateTime.Parse(transaction.DateCreated);
                                logger.LogDebug($"Found transfer on {transactionDate}. ID: {transaction.Id}");

                                // if the transfer initiated from Venmo was before the toDate and after 5 days before
                                // the toDate set the transaction as the toTransfer
                                if (toTransfer == null &&
                                    transactionDate < toDate.ToDateTime(TimeOnly.MinValue) &&
                                    transactionDate > toDate.AddDays(-5).ToDateTime(TimeOnly.MinValue))
                                {
                                    logger.LogDebug($"Set transfer {transaction.Id} as toTransfer");
                                    toTransfer = transaction;
                                    transactions.Add(transaction);
                                }

                                // need to handle transfers done one after another (due to Venmo transfer limit)
                                if (toTransfer != null && previousTransaction != null && previousTransaction.Type == "transfer")
                                {
                                    logger.LogDebug($"Found transfers one after another\n" +
                                                    $"Transfer 1: {previousTransaction.Id} at {previousTransaction.DateCreated}\n" +
                                                    $"Transfer 2: {transaction.Id} at {transaction.DateCreated}");
                                    transactions.Add(transaction);
                                }

                                if (fromTransfer == null &&
                                    transactionDate < fromDate.ToDateTime(TimeOnly.MinValue) &&
                                    transactionDate > fromDate.AddDays(-5).ToDateTime(TimeOnly.MinValue))
                                {
                                    logger.LogDebug($"Set transfer {transaction.Id} as fromTransfer");
                                    fromTransfer = transaction;
                                    transactions.Add(transaction);
                                    foundAllTransactions = true;
                                    break;
                                }
                            }
                            else if (transaction.Type == "payment")
                            {
                                // if the user received money, either someone paid them or they charged someone
                                if ((transaction.Payment !.Action == "pay" && transaction.Payment.Target !.User.Id == venmoUser.Venmo !.UserId) ||
                                    (transaction.Payment.Action == "charge" && transaction.Payment.Actor !.Id == venmoUser.Venmo !.UserId))
                                {
                                    DateTime transactionDate = DateTime.Parse(transaction.DateCreated);
                                    if (toTransfer != null)
                                    {
                                        if (fromTransfer == null)
                                        {
                                            if (transactionDate < DateTime.Parse(toTransfer.DateCreated !))
                                            {
                                                transactions.Add(transaction);
                                            }
                                        }
                                    }
                                }
                            }
                            previousTransaction = transaction;
                        }
                    }

                    if (transactionsResponse.Data.Count == 0)
                    {
                        break;
                    }
                    beforeId = previousTransaction !.Id;
                }
            }while (!foundAllTransactions);

            return(transactions);
        }
Esempio n. 20
0
 /// <summary>
 /// 10 weeks from the provided date
 /// </summary>
 public static DateOnly WeeksFrom(DateOnly date)
 {
     return(date.AddDays(70));
 }