private static void InitCustomers() { DateTimeOffset dto = new DateTimeOffset(2015, 1, 1, 1, 2, 3, 4, TimeSpan.Zero); _customers = Enumerable.Range(1, 5).Select(e => new DCustomer { Id = e, DateTime = dto.AddYears(e).DateTime, Offset = e % 2 == 0 ? dto.AddMonths(e) : dto.AddDays(e).AddMilliseconds(10), Date = e % 2 == 0 ? dto.AddDays(e).Date : dto.AddDays(-e).Date, TimeOfDay = e % 3 == 0 ? dto.AddHours(e).TimeOfDay : dto.AddHours(-e).AddMilliseconds(10).TimeOfDay, NullableDateTime = e % 2 == 0 ? (DateTime?)null : dto.AddYears(e).DateTime, NullableOffset = e % 3 == 0 ? (DateTimeOffset?)null : dto.AddMonths(e), NullableDate = e % 2 == 0 ? (Date?)null : dto.AddDays(e).Date, NullableTimeOfDay = e % 3 == 0 ? (TimeOfDay?)null : dto.AddHours(e).TimeOfDay, DateTimes = new [] { dto.AddYears(e).DateTime, dto.AddMonths(e).DateTime }, Offsets = new [] { dto.AddMonths(e), dto.AddDays(e) }, Dates = new [] { (Date)dto.AddYears(e).Date, (Date)dto.AddMonths(e).Date }, TimeOfDays = new [] { (TimeOfDay)dto.AddHours(e).TimeOfDay, (TimeOfDay)dto.AddMinutes(e).TimeOfDay }, NullableDateTimes = new [] { dto.AddYears(e).DateTime, (DateTime?)null, dto.AddMonths(e).DateTime }, NullableOffsets = new [] { dto.AddMonths(e), (DateTimeOffset?)null, dto.AddDays(e) }, NullableDates = new [] { (Date)dto.AddYears(e).Date, (Date?)null, (Date)dto.AddMonths(e).Date }, NullableTimeOfDays = new [] { (TimeOfDay)dto.AddHours(e).TimeOfDay, (TimeOfDay?)null, (TimeOfDay)dto.AddMinutes(e).TimeOfDay }, }).ToList(); }
static void Main(string[] args) { WorkingWithTimeZone(); WorkingWithDateTimeOffset(); WorkingWithISO8601(); // Converting string to DateTime or DateTimeOffset var date = "9/10/2019 10:00:00 PM"; var parsedDate1 = DateTime.ParseExact(date, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); Console.WriteLine(parsedDate1); var date2 = "9/10/2019 10:00:00 PM +02:00"; var parsedDate2 = DateTime.Parse(date2, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); Console.WriteLine(parsedDate2); Console.WriteLine(parsedDate2.Kind); //Local/UTC WorkingWithDateTimeArithmetic(); WorkingWithCalendar(); // Extending Contracts var contractDate = new DateTimeOffset(2019, 7, 1, 0, 0, 0, TimeSpan.Zero); Console.WriteLine(contractDate); contractDate = contractDate.AddMonths(6).AddTicks(-1); Console.WriteLine(contractDate); }
public async Task PerformBackupIfApplicable(IChannelSettings settings) { if (settings.SettingsBackupRate != SettingsBackupRateEnum.None && !string.IsNullOrEmpty(settings.SettingsBackupLocation)) { DateTimeOffset newResetDate = settings.SettingsLastBackup; if (settings.SettingsBackupRate == SettingsBackupRateEnum.Daily) { newResetDate = newResetDate.AddDays(1); } else if (settings.SettingsBackupRate == SettingsBackupRateEnum.Weekly) { newResetDate = newResetDate.AddDays(7); } else if (settings.SettingsBackupRate == SettingsBackupRateEnum.Monthly) { newResetDate = newResetDate.AddMonths(1); } if (newResetDate < DateTimeOffset.Now) { string filePath = Path.Combine(settings.SettingsBackupLocation, settings.Channel.id + "-Backup-" + DateTimeOffset.Now.ToString("MM-dd-yyyy") + ".mixitup"); await this.SavePackagedBackup(settings, filePath); settings.SettingsLastBackup = DateTimeOffset.Now; } } }
/// <summary> /// Adds the specified number of months to the DateTimeOffset object /// </summary> /// <param name="startDateTime">The date to add months to</param> /// <param name="months">The number of months to add</param> /// <returns>A DateTimeOffset object with the specified number of months added</returns> public static DateTimeOffset AddMonths(this DateTimeOffset startDateTime, double months) { // Get the number of whole and fractional months to add var wholeMonths = Math.Truncate(months); var partialMonth = months - wholeMonths; // Get the date when only whole months are considered var newDateTime = startDateTime.AddMonths((int)wholeMonths); if (partialMonth > 0) { // Calculate the number of days to add that correspond to the fractional number of months // Get the number of days that would be in the entire next month after the date that results when only whole months are added. // We do this because the number of days in the subsequent month can vary between 28 and 31. var tempStep = newDateTime.AddMonths(1); var daysInNextMonth = (tempStep - newDateTime).TotalDays; // Get the number of days from that next month that should be added to the resulting date/time var daysInNextStep = partialMonth * daysInNextMonth; // Add the days to the whole-months-only date/time newDateTime = newDateTime.AddDays(daysInNextStep); } return(newDateTime); }
public static DateTimeOffset ExtendContract(DateTimeOffset current, int months) { var newContractDate = current.AddMonths(months).AddTicks(-1); return(new DateTimeOffset(newContractDate.Year, newContractDate.Month, DateTime.DaysInMonth(newContractDate.Year, newContractDate.Month), 23, 59, 59, current.Offset)); }
private bool CanCalculate(IReadOnlyCollection <Event> events, DateTimeOffset now) { var eventEnough = CountEventWithRating(events); if (eventEnough <= ThresholdEventsWithRating) { return(false); } var earliestEventDate = EarliestEventDate(events); if (now.AddMonths(-MaxMonthThreshold) < earliestEventDate) { return(false); } _worstRatingEventInfo = events .Where(@event => @event.CustomizationsParameters.Rating.IsSome) .Select(x => new WorstRatingEventInfo { Event = x, Rating = x.CustomizationsParameters.Rating.ValueUnsafe() }) .OrderBy(x => x.Rating).First(); if (_worstRatingEventInfo.Event.HappensDate > now.AddDays(-MinDaysThreshold)) { return(false); } return(true); }
private static DateTimeOffset TranslatedAdd(DateTimeOffset date, IntervalUnit unit, int amountToAdd) { switch (unit) { case IntervalUnit.Day: return(date.AddDays(amountToAdd)); case IntervalUnit.Hour: return(date.AddHours(amountToAdd)); case IntervalUnit.Minute: return(date.AddMinutes(amountToAdd)); case IntervalUnit.Month: return(date.AddMonths(amountToAdd)); case IntervalUnit.Second: return(date.AddSeconds(amountToAdd)); case IntervalUnit.Millisecond: return(date.AddMilliseconds(amountToAdd)); case IntervalUnit.Week: return(date.AddDays(amountToAdd * 7)); case IntervalUnit.Year: return(date.AddYears(amountToAdd)); default: throw new ArgumentException("Unknown IntervalUnit"); } }
private static void SetTitle(ExcelWorksheet worksheet, DivisionDto division, DateTimeOffset dueDate) { var company = "PT DAN LIRIS"; var title = "LAPORAN BUDGET CASH FLOW"; var divisionName = "SEMUA DIVISI"; if (division != null) { divisionName = $"DIVISI: {division.Name}"; } var cultureInfo = new CultureInfo("id-ID"); var date = $"PERIODE {dueDate.AddMonths(1).DateTime.ToString("MMMM yyyy", cultureInfo)}"; worksheet.Cells["A1"].Value = company; worksheet.Cells["A1:H1"].Merge = true; worksheet.Cells["A1:H1"].Style.Font.Size = 20; worksheet.Cells["A1:H1"].Style.Font.Bold = true; worksheet.Cells["A2"].Value = title; worksheet.Cells["A2:H2"].Merge = true; worksheet.Cells["A2:H2"].Style.Font.Size = 20; worksheet.Cells["A2:H2"].Style.Font.Bold = true; worksheet.Cells["A3"].Value = divisionName; worksheet.Cells["A3:H3"].Merge = true; worksheet.Cells["A3:H3"].Style.Font.Size = 20; worksheet.Cells["A3:H3"].Style.Font.Bold = true; worksheet.Cells["A4"].Value = date; worksheet.Cells["A4:H4"].Merge = true; worksheet.Cells["A4:H4"].Style.Font.Size = 20; worksheet.Cells["A4:H4"].Style.Font.Bold = true; }
private DateTimeOffset OldestDateForUserActivity() { var currentDate = DateTimeOffset.Now; var firstOfCurrentMonth = new DateTimeOffset(currentDate.Year, currentDate.Month, 1, 0, 0, 0, TimeZoneInfo.Local.GetUtcOffset(currentDate)); return(firstOfCurrentMonth.AddMonths(-2)); }
public void CreateNewKey_CallsInternalManager() { // Arrange - mocks DateTimeOffset minCreationDate = DateTimeOffset.UtcNow; DateTimeOffset?actualCreationDate = null; DateTimeOffset activationDate = minCreationDate + TimeSpan.FromDays(7); DateTimeOffset expirationDate = activationDate.AddMonths(1); var mockInternalKeyManager = new Mock <IInternalXmlKeyManager>(); mockInternalKeyManager .Setup(o => o.CreateNewKey(It.IsAny <Guid>(), It.IsAny <DateTimeOffset>(), activationDate, expirationDate)) .Callback <Guid, DateTimeOffset, DateTimeOffset, DateTimeOffset>((innerKeyId, innerCreationDate, innerActivationDate, innerExpirationDate) => { actualCreationDate = innerCreationDate; }); // Arrange - services var serviceCollection = new ServiceCollection(); serviceCollection.AddSingleton <IXmlRepository>(new Mock <IXmlRepository>().Object); serviceCollection.AddSingleton <IAuthenticatedEncryptorConfiguration>(new Mock <IAuthenticatedEncryptorConfiguration>().Object); serviceCollection.AddSingleton <IInternalXmlKeyManager>(mockInternalKeyManager.Object); var services = serviceCollection.BuildServiceProvider(); var keyManager = new XmlKeyManager(services); // Act keyManager.CreateNewKey(activationDate, expirationDate); // Assert Assert.InRange(actualCreationDate.Value, minCreationDate, DateTimeOffset.UtcNow); }
protected override async Task <SecretData> RotateValue(Parameters parameters, RotationContext context, CancellationToken cancellationToken) { DateTimeOffset now = _clock.UtcNow; CloudStorageAccount account = CloudStorageAccount.Parse(await context.GetSecretValue(parameters.ConnectionString)); CloudBlobClient blobClient = account.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(parameters.Container); CloudBlob blob = container.GetBlobReference(parameters.Blob); string sas = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy { Permissions = SharedAccessBlobPolicy.PermissionsFromString(parameters.Permissions), SharedAccessExpiryTime = now.AddMonths(1), }); string result = blob.Uri.AbsoluteUri + sas; return(new SecretData(result, now.AddMonths(1), now.AddDays(15))); }
public BillingLineItem GetValidRequest() { var now = DateTime.Now; var startMonth = new DateTimeOffset(now.Year, now.Month, 1, 0, 0, 0, new TimeSpan(0, 0, 0)); //var startMonth = new DateTimeOffset(now).ToOffset(TimeSpan.Zero); return(new BillingLineItem { OrderId = newOrderId, PlannerId = DataClass.PlannerOnly[0].Id, BillingLineProductId = newProductId, StartMonth = startMonth, DurationInMonths = 2, BillingLineBuyingAreaRevenues = new List <BillingLineBuyingAreaRevenue>() { new BillingLineBuyingAreaRevenue() { Id = newBuyingAreaId, MonthBuyingAreaRevenues = new List <MonthBuyingAreaRevenue>() { new MonthBuyingAreaRevenue() { Date = startMonth, Value = 50.60M }, new MonthBuyingAreaRevenue() { Date = startMonth.AddMonths(1), Value = 89.99M } } } } }); }
private static DateTimeOffset CalculateEndDate(Meeting.EventRecurrence recurrence) { DateTimeOffset date = DateTimeOffset.Parse(recurrence.Range.StartDate); int rangeValue = (recurrence.Range.NumberOfOccurrences - 1) * recurrence.Pattern.Interval; switch (recurrence.Pattern.Type.ToLower()) { case OData.Daily: date = date.AddDays(rangeValue); break; case OData.Weekly: int occurrences = recurrence.Range.NumberOfOccurrences / recurrence.Pattern.DaysOfWeek.Count; date = date.AddDays(CalculateDayDiff(date, recurrence.Pattern.DaysOfWeek)); date = date.AddDays(7 * (occurrences - 1) * recurrence.Pattern.Interval); break; case OData.AbsoluteMonthly: case OData.RelativeMonthly: date = date.AddMonths(rangeValue); break; case OData.AbsoluteYearly: case OData.RelativeYearly: date = date.AddYears(rangeValue); break; } return(date); }
private static void SetTitle(ExcelWorksheet worksheet, UnitDto unit, DateTimeOffset dueDate) { var company = "PT DAN LIRIS"; var title = "LAPORAN BUDGET CASH FLOW"; var unitName = "UNIT: "; if (unit != null) { unitName += unit.Name; } var cultureInfo = new CultureInfo("id-ID"); var date = $"PERIODE {dueDate.AddMonths(1).DateTime.ToString("MMMM yyyy", cultureInfo)}"; worksheet.Cells["A1"].Value = company; worksheet.Cells["A1:H1"].Merge = true; worksheet.Cells["A1:H1"].Style.Font.Size = 20; worksheet.Cells["A1:H1"].Style.Font.Bold = true; worksheet.Cells["A2"].Value = title; worksheet.Cells["A2:H2"].Merge = true; worksheet.Cells["A2:H2"].Style.Font.Size = 20; worksheet.Cells["A2:H2"].Style.Font.Bold = true; worksheet.Cells["A3"].Value = unitName; worksheet.Cells["A3:H3"].Merge = true; worksheet.Cells["A3:H3"].Style.Font.Size = 20; worksheet.Cells["A3:H3"].Style.Font.Bold = true; worksheet.Cells["A4"].Value = date; worksheet.Cells["A4:H4"].Merge = true; worksheet.Cells["A4:H4"].Style.Font.Size = 20; worksheet.Cells["A4:H4"].Style.Font.Bold = true; }
public IHttpActionResult ResetDataSource() { DateAndTimeOfDayContext db = new DateAndTimeOfDayContext(); if (!db.Customers.Any()) { DateTimeOffset dateTime = new DateTimeOffset(2014, 12, 24, 1, 2, 3, 4, new TimeSpan(-8, 0, 0)); IEnumerable <EfCustomer> customers = Enumerable.Range(1, 5).Select(e => new EfCustomer { Id = e, DateTime = dateTime.AddYears(e).AddHours(e).AddMilliseconds(e).DateTime, NullableDateTime = e % 2 == 0 ? (DateTime?)null : dateTime.AddHours(e * 5).AddMilliseconds(e * 5).DateTime, Offset = dateTime.AddMonths(e).AddHours(e).AddMilliseconds(e), NullableOffset = e % 3 == 0 ? (DateTimeOffset?)null : dateTime.AddDays(e).AddHours(e * 5) }).ToList(); foreach (EfCustomer customer in customers) { db.Customers.Add(customer); } db.SaveChanges(); } return(Ok()); }
private static DateTimeOffset?GetValidThroughTime(MediaWiki wiki, string title, DateTimeOffset date) { var oldDate = date.AddMonths(-3); var history = wiki.GetHistory(title, oldDate); if (history == null) { return(null);// article doesn't exist } if (history.Length == 0) { return(DateTimeOffset.MinValue); // no revisions for 3 months, thus not valid } // retreiving immediate parent of the first "3 months old" edit // or faking the "creation" with a zero-sized revision var parentId = history.First().ParentId; var parent = parentId == 0 ? null : wiki.GetRevisionInfo(parentId); parent = parent ?? new MediaWiki.RevisionInfo(); parent.Timestamp = oldDate.AddTicks(-1); // searching for the first revision that makes article non-valid foreach (var entry in new[] { parent }.Concat(history)) { var newDate = entry.Timestamp.AddMonths(3); var newSize = GetArticleSize(newDate, history); if (entry.Size * 2 > newSize) { return(newDate == parent.Timestamp.AddMonths(3) ? DateTimeOffset.MinValue : newDate); } } throw new Exception("Impossible..."); }
public async Task <ActionResult <IEnumerable <RaidDto> > > GetMine() { var userId = User.GetDiscordId(); var characterIds = await _context.UserClaims .AsNoTracking() .Where(claim => claim.UserId == userId && claim.ClaimType == AppClaimTypes.Character) .Select(claim => claim.ClaimValue) .ToListAsync(); var ids = new HashSet <long>(); foreach (var characterIdString in characterIds) { if (long.TryParse(characterIdString, out var characterId)) { ids.Add(characterId); } } DateTimeOffset end = DateTimeOffset.UtcNow, start = end.AddMonths(-1); return(await _context.Raids .AsNoTracking() .Where(r => r.StartedAt >= start && r.StartedAt < end && r.Attendees.Any(a => ids.Contains(a.CharacterId))) .OrderByDescending(r => r.StartedAt) .Select(r => new RaidDto { Id = r.Id, Phase = r.Phase, StartedAt = r.StartedAt, TeamId = r.RaidTeamId, TeamName = r.RaidTeam.Name }) .ToListAsync()); }
public void CreateNewKey_CallsInternalManager() { // Arrange DateTimeOffset minCreationDate = DateTimeOffset.UtcNow; DateTimeOffset?actualCreationDate = null; DateTimeOffset activationDate = minCreationDate + TimeSpan.FromDays(7); DateTimeOffset expirationDate = activationDate.AddMonths(1); var mockInternalKeyManager = new Mock <IInternalXmlKeyManager>(); mockInternalKeyManager .Setup(o => o.CreateNewKey(It.IsAny <Guid>(), It.IsAny <DateTimeOffset>(), activationDate, expirationDate)) .Callback <Guid, DateTimeOffset, DateTimeOffset, DateTimeOffset>((innerKeyId, innerCreationDate, innerActivationDate, innerExpirationDate) => { actualCreationDate = innerCreationDate; }); var options = Options.Create(new KeyManagementOptions() { AuthenticatedEncryptorConfiguration = new Mock <AlgorithmConfiguration>().Object, XmlRepository = new Mock <IXmlRepository>().Object, XmlEncryptor = null }); var keyManager = new XmlKeyManager(options, SimpleActivator.DefaultWithoutServices, NullLoggerFactory.Instance, mockInternalKeyManager.Object); // Act keyManager.CreateNewKey(activationDate, expirationDate); // Assert Assert.InRange(actualCreationDate.Value, minCreationDate, DateTimeOffset.UtcNow); }
private DateTimeOffset DateTransformerWithAllArgs(DateTimeOffset date, string durationString, string dateString) { DateTimeOffset newDate; // creates date with specific offset value switch (dateString) { case "today": newDate = new DateTimeOffset(date.Date, date.Offset); break; case "this month": newDate = new DateTimeOffset(date.Year, date.Month, 1, 0, 0, 0, date.Offset); break; case "this week": DateTime weekDate = date.Subtract(TimeSpan.FromDays((int)date.DayOfWeek - 1)).Date; newDate = new DateTimeOffset(weekDate, date.Offset); break; case "this year": newDate = new DateTimeOffset(date.Year, 1, 1, 0, 0, 0, date.Offset); break; case "now": newDate = date; break; default: throw new ArgumentOutOfRangeException($"Invalid Date string Specified : {dateString}"); } //set the date variations foreach (string value in durationString.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)) { Match match = Regex.Match(value, "([+-]?\\d+)([w|s|m|h|d|M|y])"); int duration = Convert.ToInt16(match.Groups[1].Value); char placeholder = Convert.ToChar(match.Groups[2].Value); switch (placeholder) { case 's': newDate = newDate.AddSeconds(duration); break; case 'm': newDate = newDate.AddMinutes(duration); break; case 'h': newDate = newDate.AddHours(duration); break; case 'd': newDate = newDate.AddDays(duration); break; case 'M': newDate = newDate.AddMonths(duration); break; case 'w': newDate = newDate.AddDays(duration * 7); break; case 'y': newDate = newDate.AddYears(duration); break; default: throw new ArgumentOutOfRangeException($"Invalid placeholder Specified : {placeholder}"); } } return(newDate); }
/// <summary> /// Gets the start and end date of the month, matching the passed <see cref="DateTimeOffset"/> instance. /// </summary> /// <param name="at">The <see cref="DateTimeOffset"/>.</param> /// <returns>The start and end dates.</returns> public static (DateTimeOffset, DateTimeOffset) GetMonthDates(this DateTimeOffset at) { var startAt = new DateTimeOffset(at.Year, at.Month, 1, 0, 0, 0, new TimeSpan()); var endAt = startAt.AddMonths(1).AddSeconds(-1); return(startAt, endAt); }
public TimeSeriesViewModel() { this.ItemsSourceList = new ObservableCollection <TimeSeriesData>(); var first = new TimeSeriesData(0); DateTimeOffset now = DateTimeOffset.Now; for (int i = 0; i < 30; i++) { var t = now.AddMonths(i); var v = i / 1.0; var y = Math.Abs(v) < 1e-10 ? 1 : Math.Sin(v) / v; var pt = new TimeSeriesPoint(t, y); first.DataList.Add(pt); } this.ItemsSourceList.Add(first); for (int i = 1; i < 3; i++) { var list = new TimeSeriesData(i); double yOffset = i * 0.5; foreach (var item in first.DataList) { list.DataList.Add(new TimeSeriesPoint(item.t, item.Y + yOffset)); } this.ItemsSourceList.Add(list); } }
static void Main(string[] args) { var contractDate = new DateTimeOffset(2019, 7, 1, 0, 0, 0, TimeSpan.Zero); Console.WriteLine(contractDate); contractDate = contractDate.AddMonths(6).AddTicks(-1); Console.WriteLine(contractDate); var start = new DateTimeOffset(2007, 12, 31, 0, 0, 0, TimeSpan.Zero); var week = calendar.GetWeekOfYear(start.DateTime, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); Console.WriteLine(week); var timeSpan = new TimeSpan(60, 100, 200); Console.WriteLine(timeSpan.Days); Console.WriteLine(timeSpan.Hours); Console.WriteLine(timeSpan.TotalMilliseconds); var start1 = DateTimeOffset.UtcNow; var end = start.AddSeconds(45); TimeSpan difference = end - start1; Console.WriteLine(difference.Seconds); difference = difference.Multiply(2); }
public async Task InitializesTheMonthsPropertyToTheMonthsToShow() { var observer = TestScheduler.CreateObserver <IImmutableList <ReportsCalendarPageViewModel> >(); var now = new DateTimeOffset(2020, 4, 2, 1, 1, 1, TimeSpan.Zero); TimeService.CurrentDateTime.Returns(now); TimeService.MidnightObservable.Returns(Observable.Never <DateTimeOffset>()); await ViewModel.Initialize(); ViewModel.MonthsObservable.Subscribe(observer); TestScheduler.Start(); var months = observer.Values().First(); months.Should().HaveCount(ReportsCalendarViewModel.MonthsToShow); var firstDateTime = now.AddMonths(-(ReportsCalendarViewModel.MonthsToShow - 1)); var month = new CalendarMonth( firstDateTime.Year, firstDateTime.Month); for (int i = 0; i < (ReportsCalendarViewModel.MonthsToShow - 1); i++, month = month.Next()) { months[i].CalendarMonth.Should().Be(month); } }
public bool Parse(ParserContext context, string field) { var match = TimeOfObservationRegex.Match(field); if (!match.Success) { return(false); } var day = int.Parse(match.Groups[Day].Value); var hour = int.Parse(match.Groups[Hour].Value); var minutes = int.Parse(match.Groups[Minutes].Value); var now = _dateTimeProvider.Now; var timeOfObservation = new DateTimeOffset(now.Year, now.Month, day, hour, minutes, 0, TimeSpan.Zero); if (timeOfObservation > now) { timeOfObservation = timeOfObservation.AddMonths(-1); } context.Metar.TimeOfObservation = timeOfObservation; return(true); }
public EfCustomersController(DateAndTimeOfDayContext context) { context.Database.EnsureCreated(); _db = context; if (!context.Customers.Any()) { DateTimeOffset dateTime = new DateTimeOffset(2014, 12, 24, 1, 2, 3, 4, new TimeSpan(-8, 0, 0)); IEnumerable <EfCustomer> customers = Enumerable.Range(1, 5).Select(e => new EfCustomer { // Id = e, DateTime = dateTime.AddYears(e).AddHours(e).AddMilliseconds(e).DateTime, NullableDateTime = e % 2 == 0 ? (DateTime?)null : dateTime.AddHours(e * 5).AddMilliseconds(e * 5).DateTime, Offset = dateTime.AddMonths(e).AddHours(e).AddMilliseconds(e), NullableOffset = e % 3 == 0 ? (DateTimeOffset?)null : dateTime.AddDays(e).AddHours(e * 5) }).ToList(); foreach (EfCustomer customer in customers) { context.Customers.Add(customer); } context.SaveChanges(); } }
// -------------------------------------------------------------------------------- public static DateTimeOffset Ceiling(this DateTimeOffset dto, DateTimeFieldEnum field) { switch (field) { case DateTimeFieldEnum.MILLISEC: { dto = dto.AddTicks(9999); return(new DateTimeOffset(dto.Year, dto.Month, dto.Day, dto.Hour, dto.Minute, dto.Second, dto.Millisecond, dto.Offset)); } case DateTimeFieldEnum.SECOND: { dto = dto.AddMilliseconds(999); return(new DateTimeOffset(dto.Year, dto.Month, dto.Day, dto.Hour, dto.Minute, dto.Second, 0, dto.Offset)); } case DateTimeFieldEnum.MINUTE: { dto = dto.AddSeconds(59); return(new DateTimeOffset(dto.Year, dto.Month, dto.Day, dto.Hour, dto.Minute, 0, 0, dto.Offset)); } case DateTimeFieldEnum.HOUR: { dto = dto.AddMinutes(59); return(new DateTimeOffset(dto.Year, dto.Month, dto.Day, dto.Hour, 0, 0, 0, dto.Offset)); } case DateTimeFieldEnum.DAY: case DateTimeFieldEnum.DATE: { var baseDto = new DateTimeOffset(dto.Year, dto.Month, dto.Day, 0, 0, 0, 0, dto.Offset); if (baseDto == dto) { return(baseDto); } return(baseDto.AddDays(1)); } case DateTimeFieldEnum.MONTH: { var baseDto = new DateTimeOffset(dto.Year, dto.Month, 1, 0, 0, 0, 0, dto.Offset); if (baseDto == dto) { return(baseDto); } return(baseDto.AddMonths(1)); } case DateTimeFieldEnum.YEAR: { var baseDto = new DateTimeOffset(dto.Year, 1, 1, 0, 0, 0, 0, dto.Offset); if (baseDto == dto) { return(baseDto); } return(baseDto.AddYears(1)); } default: throw new NotSupportedException(); } }
/// <summary>When the event last occurred before 'time'</summary> public DateTimeOffset Prev(DateTimeOffset?time = null) { var now = time ?? DateTimeOffset.Now; switch (Repeat) { case ERepeat.OneOff: { return(Time); } case ERepeat.Minutely: { var when = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, now.Minute, Time.Second, Time.Millisecond, now.Offset); if (when >= now) when = when.AddMinutes(-1); return(when); } case ERepeat.Hourly: { var when = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, Time.Minute, Time.Second, Time.Millisecond, now.Offset); if (when >= now) when = when.AddHours(-1); return(when); } case ERepeat.Daily: { var when = new DateTimeOffset(now.Year, now.Month, now.Day, Time.Hour, Time.Minute, Time.Second, Time.Millisecond, now.Offset); if (when >= now) when = when.AddDays(-1); return(when); } case ERepeat.Weekly: { var when = new DateTimeOffset(now.Year, now.Month, Time.Day, Time.Hour, Time.Minute, Time.Second, Time.Millisecond, now.Offset); if (when >= now) when = when.AddDays(-7); return(when); } case ERepeat.Monthly: { var when = new DateTimeOffset(now.Year, now.Month, Time.Day, Time.Hour, Time.Minute, Time.Second, Time.Millisecond, now.Offset); if (when >= now) when = when.AddMonths(-1); return(when); } case ERepeat.Yearly: { var when = new DateTimeOffset(now.Year, Time.Month, Time.Day, Time.Hour, Time.Minute, Time.Second, Time.Millisecond, now.Offset); if (when >= now) when = when.AddYears(-1); return(when); } default: { throw new Exception($"Unknown repeat type: {Repeat}"); } } }
/// <summary> /// Extend a contract by the whole month and not by just adding a months time. /// ex. 02-29 to 03-28 should actually be 02-29 to 03-31 /// </summary> /// <param name="current"></param> /// <param name="months"></param> /// <returns></returns> static DateTimeOffset ExtendContract(DateTimeOffset current, int months) { // add months to get the current month this contract should end var newContractDate = current.AddMonths(months).AddTicks(-1); return(new DateTimeOffset(newContractDate.Year, newContractDate.Month, DateTime.DaysInMonth(newContractDate.Year, newContractDate.Month), 23, 59, 59, current.Offset)); }
public void DateNotInPeriodThrows(DateTimeOffset value) { var period = Period.Open(value); var ex = Assert.Throws <ClosingDateBeforePeriodException>(() => period.MustNotBeAfter(value.AddMonths(-1))); Assert.Equal(value.AddMonths(-1), ex.Date); Assert.Equal(period, ex.Period); }
public override DateRangeParameter GetDateRange() { var now = TimeService.CurrentDateTime.Date; var start = new DateTimeOffset(now.Year, now.Month, 1, 0, 0, 0, TimeSpan.Zero); var end = start.AddMonths(1).AddDays(-1); return(DateRangeParameter.WithDates(start, end)); }
public static IEnumerable <File> CreateFiles() { DateTimeOffset dateTime = new DateTimeOffset(2021, 4, 15, 16, 24, 8, TimeSpan.FromHours(-8)); // #2 is used for update/get round trip, its value will be changed every test running. // #3 is used for get, will never change its value. // #4 is used to select date time property, will never change its value. // #6 is used for create/get round trip, it will create, get, delete return(Enumerable.Range(1, 5).Select(e => new File { // FileId = e, Name = "File #" + e, CreatedDate = dateTime.AddMonths(3 - e).AddYears(e % 2 == 0 ? e : -e), DeleteDate = dateTime.AddMonths(e % 2 == 0 ? e : -e), })); }
public void CreateAbonnements(int kundeId, DateTimeOffset start, DateTimeOffset stop) { var period = ((stop.Year - start.Year) * 12) + stop.Month - start.Month; if (period == 0) { _context.Abonnements.Add(new Data.Abonnement(kundeId, start.Year, start.Month, true)); } else { for (int i = 0; i < period; i++) { _context.Abonnements.Add(new Data.Abonnement(kundeId, start.AddMonths(i).Year, start.AddMonths(i).Month, true)); } } _context.SaveChanges(); }
private static List<Event> GetEvents(DateTimeOffset may, DateTimeOffset june) { var inRange = new Event { StartDateTime = may, EndDateTime = june }; var startBeforeRangeEndsInRange = new Event { StartDateTime = may.AddMonths(-1), EndDateTime = june }; var startInRangeEndsAfterRange = new Event { StartDateTime = may, EndDateTime = june.AddMonths(1) }; var startsAndEndsAfterRange = new Event { StartDateTime = may.AddMonths(2), EndDateTime = june.AddMonths(2) }; var startsAndEndsBeforRange = new Event { StartDateTime = may.AddMonths(-2), EndDateTime = june.AddMonths(-2) }; var events = new List<Event> { startsAndEndsBeforRange, startBeforeRangeEndsInRange, inRange, startInRangeEndsAfterRange, startsAndEndsAfterRange, }; return events; }
public void CanAddMonthsAcrossDstTransition() { var tz = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); var dto = new DateTimeOffset(2015, 2, 9, 0, 0, 0, TimeSpan.FromHours(-8)); var result = dto.AddMonths(1, tz); var expected = new DateTimeOffset(2015, 3, 9, 0, 0, 0, TimeSpan.FromHours(-7)); Assert.Equal(expected, result); Assert.Equal(expected.Offset, result.Offset); }
public static IEnumerable<DateTimeOffset> GetSundaysInMonth(this DateTimeOffset date) { DateTimeOffset start = new DateTimeOffset(date.Year, date.Month, 1, 0, 0, 0, DateTimeOffset.Now.Offset); var sunday = date.GetSundayNearMonthsBegin(); while (sunday < start.AddMonths(1)) { yield return sunday; sunday = sunday.AddDays(7); } }
/// <summary> /// Parses the time in day hour minute format.. /// </summary> /// <param name="reference">The reference.</param> /// <param name="dayHourMinute">The time string in day hour minute format.</param> /// <returns>DateTimeOffset.</returns> public static DateTimeOffset ParseDayHourMinute(DateTimeOffset reference, string dayHourMinute) { if (reference == DateTimeOffset.MinValue || reference == DateTimeOffset.MaxValue) reference = DateTimeOffset.UtcNow; int dayOfMonth, hour, minute; int.TryParse(dayHourMinute.Substring(0, 2), out dayOfMonth); int.TryParse(dayHourMinute.Substring(2, 2), out hour); int.TryParse(dayHourMinute.Substring(4, 2), out minute); if (dayOfMonth != reference.Day) { // Check for previous month if (dayOfMonth > 25 && reference.Day < 5) reference = reference.AddMonths(-1); // Next month else if (dayOfMonth < 5 && reference.Day > 25) reference = reference.AddMonths(1); } return new DateTimeOffset(reference.Year, reference.Month, dayOfMonth, hour, minute, 0, TimeSpan.Zero); }
public void TestDateTimeOffsetDayLightSavingWhenAddingMonth() { DateTimeOffset someNov2014 = new DateTime(2014, 11, 12, 22, 28, 11, 0, DateTimeKind.Local); DateTimeOffset someDec2014 = someNov2014.AddMonths(1); DateTimeOffset dec2014Start = new DateTimeOffset(someDec2014.Year, someDec2014.Month, 1, 0, 0, 0, someNov2014.Offset); DateTimeOffset nov2014End = dec2014Start.PreviousMoment(); DateTimeOffset nov2014Start = dec2014Start.AddMonths(-1); DateTimeOffset expectedStart = someNov2014.StartOf(TimeUnits.Month); DateTimeOffset expectedEnd = someNov2014.EndOf(TimeUnits.Month); Assert.AreEqual(expectedStart, nov2014Start); Assert.AreEqual(expectedEnd, nov2014End); }
public static void TestAddition() { DateTimeOffset dt = new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70)); Assert.Equal(17, dt.AddDays(2).Day); Assert.Equal(13, dt.AddDays(-2).Day); Assert.Equal(10, dt.AddMonths(2).Month); Assert.Equal(6, dt.AddMonths(-2).Month); Assert.Equal(1996, dt.AddYears(10).Year); Assert.Equal(1976, dt.AddYears(-10).Year); Assert.Equal(13, dt.AddHours(3).Hour); Assert.Equal(7, dt.AddHours(-3).Hour); Assert.Equal(25, dt.AddMinutes(5).Minute); Assert.Equal(15, dt.AddMinutes(-5).Minute); Assert.Equal(35, dt.AddSeconds(30).Second); Assert.Equal(2, dt.AddSeconds(-3).Second); Assert.Equal(80, dt.AddMilliseconds(10).Millisecond); Assert.Equal(60, dt.AddMilliseconds(-10).Millisecond); }
public void From_FromFixedDateTime_Tests(int value) { var originalPointInTime = new DateTimeOffset(1976, 12, 31, 17, 0, 0, 0, TimeSpan.Zero); Assert.AreEqual(value.Years().From(originalPointInTime), originalPointInTime.AddYears(value)); Assert.AreEqual(value.Months().From(originalPointInTime), originalPointInTime.AddMonths(value)); Assert.AreEqual(value.Weeks().From(originalPointInTime), originalPointInTime.AddDays(value*DaysPerWeek)); Assert.AreEqual(value.Days().From(originalPointInTime), originalPointInTime.AddDays(value)); Assert.AreEqual(value.Hours().From(originalPointInTime), originalPointInTime.AddHours(value)); Assert.AreEqual(value.Minutes().From(originalPointInTime), originalPointInTime.AddMinutes(value)); Assert.AreEqual(value.Seconds().From(originalPointInTime), originalPointInTime.AddSeconds(value)); Assert.AreEqual(value.Milliseconds().From(originalPointInTime), originalPointInTime.AddMilliseconds(value)); Assert.AreEqual(value.Ticks().From(originalPointInTime), originalPointInTime.AddTicks(value)); }
public void Between() { var date = new DateTimeOffset(2015, 8, 7, 13, 26, 30, TimeSpan.Zero); Assert.IsTrue(date.Between(date.AddMonths(-3), date.AddMonths(3))); Assert.IsTrue(date.AddHours(36).Between(date.AddMonths(-3), date.AddMonths(3))); Assert.IsFalse(date.AddMonths(6).Between(date.AddMonths(-3), date.AddMonths(3))); Assert.IsFalse(date.AddHours(-2).Between(date, date.AddMonths(3))); Assert.IsTrue(date.Between(date.AddMonths(-3), date.AddMonths(3), false)); Assert.IsTrue(date.AddHours(36).Between(date.AddMonths(-3), date.AddMonths(3), false)); Assert.IsFalse(date.AddMonths(6).Between(date.AddMonths(-3), date.AddMonths(3), false)); Assert.IsTrue(date.AddHours(-2).Between(date, date.AddMonths(3), false)); Assert.IsFalse(date.AddHours(-24).Between(date, date.AddMonths(3), false)); }
public IHttpActionResult ResetDataSource() { DateAndTimeOfDayContext db = new DateAndTimeOfDayContext(); if (!db.Customers.Any()) { DateTimeOffset dateTime = new DateTimeOffset(2014, 12, 24, 1, 2, 3, 4, new TimeSpan(-8, 0, 0)); IEnumerable<EfCustomer> customers = Enumerable.Range(1, 5).Select(e => new EfCustomer { Id = e, DateTime = dateTime.AddYears(e).AddHours(e).AddMilliseconds(e).DateTime, NullableDateTime = e % 2 == 0 ? (DateTime?)null : dateTime.AddHours(e * 5).AddMilliseconds(e * 5).DateTime, Offset = dateTime.AddMonths(e).AddHours(e).AddMilliseconds(e), NullableOffset = e % 3 == 0 ? (DateTimeOffset?)null : dateTime.AddDays(e).AddHours(e * 5) }).ToList(); foreach (EfCustomer customer in customers) { db.Customers.Add(customer); } db.SaveChanges(); } return Ok(); }
public void When_a_value_is_not_one_of_the_specified_values_it_should_throw_with_descriptive_message() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- DateTimeOffset value = new DateTimeOffset(31.December(2016), 1.Hours()); //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- Action action = () => value.Should().BeOneOf(new[] { value.AddDays(1), value.AddMonths(1) }, "because it's true"); //----------------------------------------------------------------------------------------------------------- // Assert //----------------------------------------------------------------------------------------------------------- action.ShouldThrow<AssertFailedException>() .WithMessage("Expected value to be one of {<2017-01-01 +1h>, <2017-01-31 +1h>} because it's true, but found <2016-12-31 +1h>."); }
private static DateTimeOffset TranslatedAdd(DateTimeOffset date, IntervalUnit unit, int amountToAdd) { switch (unit) { case IntervalUnit.Day: return date.AddDays(amountToAdd); case IntervalUnit.Hour: return date.AddHours(amountToAdd); case IntervalUnit.Minute: return date.AddMinutes(amountToAdd); case IntervalUnit.Month: return date.AddMonths(amountToAdd); case IntervalUnit.Second: return date.AddSeconds(amountToAdd); case IntervalUnit.Millisecond: return date.AddMilliseconds(amountToAdd); case IntervalUnit.Week: return date.AddDays(amountToAdd*7); case IntervalUnit.Year: return date.AddYears(amountToAdd); default: throw new ArgumentException("Unknown IntervalUnit"); } }
/// <summary> /// Returns an enumerable collection of log blobs containing Analytics log records. The blobs are retrieved lazily. /// </summary> /// <param name="service">A <see cref="StorageService"/> enumeration value.</param> /// <param name="startTime">A <see cref="DateTimeOffset"/> object representing the start of the time range for which logs should be retrieved.</param> /// <param name="endTime">A <see cref="DateTimeOffset"/> object representing the end of the time range for which logs should be retrieved.</param> /// <param name="operations">A <see cref="LoggingOperations"/> enumeration value that indicates the types of logging operations on which to filter the log blobs.</param> /// <param name="details">A <see cref="BlobListingDetails"/> enumeration value that indicates whether or not blob metadata should be returned. Only <c>None</c> and <c>Metadata</c> are valid values. </param> /// <param name="options">A <see cref="BlobRequestOptions"/> object that specifies additional options for the request.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> /// <returns>An enumerable collection of objects that implement <see cref="ICloudBlob"/> and are retrieved lazily.</returns> /// <remarks>Note that specifying a logging operation type for the <paramref name="operations"/> parameter will return any Analytics log blob that contains the specified logging operation, /// even if that log blob also includes other types of logging operations. Also note that the only currently supported values for the <paramref name="details"/> /// parameter are <c>None</c> and <c>Metadata</c>.</remarks> public IEnumerable<ICloudBlob> ListLogs(StorageService service, DateTimeOffset startTime, DateTimeOffset? endTime, LoggingOperations operations, BlobListingDetails details, BlobRequestOptions options, OperationContext operationContext) { CloudBlobDirectory logDirectory = this.GetLogDirectory(service); BlobListingDetails metadataDetails = details; DateTimeOffset utcStartTime = startTime.ToUniversalTime(); DateTimeOffset dateCounter = new DateTimeOffset(utcStartTime.Ticks - (utcStartTime.Ticks % TimeSpan.TicksPerHour), utcStartTime.Offset); DateTimeOffset? utcEndTime = null; string endPrefix = null; // Ensure that the date range is correct. if (endTime.HasValue) { utcEndTime = endTime.Value.ToUniversalTime(); endPrefix = logDirectory.Prefix + utcEndTime.Value.ToString("yyyy/MM/dd/HH", CultureInfo.InvariantCulture); if (utcStartTime > utcEndTime.Value) { string errorString = string.Format(CultureInfo.InvariantCulture, SR.StartTimeExceedsEndTime, startTime, endTime.Value); throw new ArgumentException(errorString); } } // Currently only support the ability to retrieve metadata on logs. if (details.HasFlag(BlobListingDetails.Copy) || details.HasFlag(BlobListingDetails.Snapshots) || details.HasFlag(BlobListingDetails.UncommittedBlobs)) { throw new ArgumentException(SR.InvalidListingDetails); } // At least one LogType must be specified. if (operations == LoggingOperations.None) { throw new ArgumentException(SR.InvalidLoggingLevel); } // If metadata or a specific LogType is specified, metadata should be retrieved. if (details.HasFlag(BlobListingDetails.Metadata) || !operations.HasFlag(LoggingOperations.All)) { metadataDetails = BlobListingDetails.Metadata; } // Check logs using an hour-based prefix until we reach a day boundary. while (dateCounter.Hour > 0) { string currentPrefix = logDirectory.Prefix + dateCounter.ToString("yyyy/MM/dd/HH", CultureInfo.InvariantCulture); IEnumerable<IListBlobItem> currentLogs = logDirectory.Container.ListBlobs(currentPrefix, true, metadataDetails, options, operationContext); foreach (ICloudBlob log in currentLogs) { if (!utcEndTime.HasValue || string.Compare(log.Parent.Prefix, endPrefix) <= 0) { if (IsCorrectLogType(log, operations)) { yield return log; } } else { yield break; } } dateCounter = dateCounter.AddHours(1); if (dateCounter > DateTimeOffset.UtcNow.AddHours(1)) { yield break; } } // Check logs using a day-based prefix until we reach a month boundary. while (dateCounter.Day > 1) { string currentPrefix = logDirectory.Prefix + dateCounter.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture); IEnumerable<IListBlobItem> currentLogs = logDirectory.Container.ListBlobs(currentPrefix, true, metadataDetails, options, operationContext); foreach (ICloudBlob log in currentLogs) { if (!utcEndTime.HasValue || string.Compare(log.Parent.Prefix, endPrefix) <= 0) { if (IsCorrectLogType(log, operations)) { yield return log; } } else { yield break; } } dateCounter = dateCounter.AddDays(1); if (dateCounter > DateTimeOffset.UtcNow.AddHours(1)) { yield break; } } // Check logs using a month-based prefix until we reach a year boundary. while (dateCounter.Month > 1) { string currentPrefix = logDirectory.Prefix + dateCounter.ToString("yyyy/MM", CultureInfo.InvariantCulture); IEnumerable<IListBlobItem> currentLogs = logDirectory.Container.ListBlobs(currentPrefix, true, metadataDetails, options, operationContext); foreach (ICloudBlob log in currentLogs) { if (!utcEndTime.HasValue || string.Compare(log.Parent.Prefix, endPrefix) <= 0) { if (IsCorrectLogType(log, operations)) { yield return log; } } else { yield break; } } dateCounter = dateCounter.AddMonths(1); if (dateCounter > DateTimeOffset.UtcNow.AddHours(1)) { yield break; } } // Continue using a year-based prefix. while (true) { string currentPrefix = logDirectory.Prefix + dateCounter.ToString("yyyy", CultureInfo.InvariantCulture); IEnumerable<IListBlobItem> currentLogs = logDirectory.Container.ListBlobs(currentPrefix, true, metadataDetails, options, operationContext); foreach (ICloudBlob log in currentLogs) { if (!utcEndTime.HasValue || string.Compare(log.Parent.Prefix, endPrefix) <= 0) { if (IsCorrectLogType(log, operations)) { yield return log; } } else { yield break; } } dateCounter = dateCounter.AddYears(1); if (dateCounter > DateTimeOffset.UtcNow.AddHours(1)) { yield break; } } }
public void ToRelativeTimeTest() { var date = new DateTimeOffset(2015, 8, 7, 13, 26, 30, TimeSpan.Zero); var now = DateTimeOffset.Now; Assert.AreEqual("now", now.ToRelativeTimeString()); Assert.AreEqual("now", now.ToRelativeTimeString(now)); Assert.AreEqual("1 second ago", date.AddSeconds(-1).ToRelativeTimeString(date)); Assert.AreEqual("10 seconds ago", date.AddSeconds(-10).ToRelativeTimeString(date)); Assert.AreEqual("1 minute ago", date.AddSeconds(-90).ToRelativeTimeString(date)); Assert.AreEqual("1 minute ago", date.AddSeconds(-100).ToRelativeTimeString(date)); Assert.AreEqual("2 minutes ago", date.AddSeconds(-120).ToRelativeTimeString(date)); Assert.AreEqual("7 minutes ago", date.AddMinutes(-7).ToRelativeTimeString(date)); Assert.AreEqual("59 minutes ago", date.AddMinutes(-59).ToRelativeTimeString(date)); Assert.AreEqual("1 hour ago", date.AddMinutes(-60).ToRelativeTimeString(date)); Assert.AreEqual("1 hour ago", date.AddHours(-1).ToRelativeTimeString(date)); Assert.AreEqual("9 hours ago", date.AddHours(-9).ToRelativeTimeString(date)); Assert.AreEqual("1 day ago", date.AddHours(-24).ToRelativeTimeString(date)); Assert.AreEqual("1 day ago", date.AddHours(-30).ToRelativeTimeString(date)); Assert.AreEqual("2 days ago", date.AddHours(-48).ToRelativeTimeString(date)); Assert.AreEqual("1 day ago", date.AddDays(-1).ToRelativeTimeString(date)); Assert.AreEqual("12 days ago", date.AddDays(-12).ToRelativeTimeString(date)); Assert.AreEqual("29 days ago", date.AddDays(-29).ToRelativeTimeString(date)); Assert.AreEqual("1 month ago", date.AddDays(-30).ToRelativeTimeString(date)); Assert.AreEqual("1 month ago", date.AddMonths(-1).ToRelativeTimeString(date)); Assert.AreEqual("3 months ago", date.AddMonths(-3).ToRelativeTimeString(date)); Assert.AreEqual("11 months ago", date.AddMonths(-11).ToRelativeTimeString(date)); Assert.AreEqual("1 year ago", date.AddMonths(-12).ToRelativeTimeString(date)); Assert.AreEqual("1 year ago", date.AddYears(-1).ToRelativeTimeString(date)); Assert.AreEqual("3 years ago", date.AddYears(-3).ToRelativeTimeString(date)); Assert.AreEqual("1 second from now", date.AddSeconds(1).ToRelativeTimeString(date)); Assert.AreEqual("10 seconds from now", date.AddSeconds(10).ToRelativeTimeString(date)); Assert.AreEqual("1 minute from now", date.AddSeconds(90).ToRelativeTimeString(date)); Assert.AreEqual("1 minute from now", date.AddSeconds(100).ToRelativeTimeString(date)); Assert.AreEqual("2 minutes from now", date.AddSeconds(120).ToRelativeTimeString(date)); Assert.AreEqual("7 minutes from now", date.AddMinutes(7).ToRelativeTimeString(date)); Assert.AreEqual("59 minutes from now", date.AddMinutes(59).ToRelativeTimeString(date)); Assert.AreEqual("1 hour from now", date.AddMinutes(60).ToRelativeTimeString(date)); Assert.AreEqual("1 hour from now", date.AddHours(1).ToRelativeTimeString(date)); Assert.AreEqual("9 hours from now", date.AddHours(9).ToRelativeTimeString(date)); Assert.AreEqual("1 day from now", date.AddDays(1).ToRelativeTimeString(date)); Assert.AreEqual("1 day from now", date.AddHours(24).ToRelativeTimeString(date)); Assert.AreEqual("12 days from now", date.AddDays(12).ToRelativeTimeString(date)); Assert.AreEqual("29 days from now", date.AddDays(29).ToRelativeTimeString(date)); Assert.AreEqual("1 month from now", date.AddDays(30).ToRelativeTimeString(date)); Assert.AreEqual("1 month from now", date.AddMonths(1).ToRelativeTimeString(date)); Assert.AreEqual("3 months from now", date.AddMonths(3).ToRelativeTimeString(date)); Assert.AreEqual("11 months from now", date.AddMonths(11).ToRelativeTimeString(date)); Assert.AreEqual("1 year from now", date.AddMonths(12).ToRelativeTimeString(date)); Assert.AreEqual("1 year from now", date.AddYears(1).ToRelativeTimeString(date)); Assert.AreEqual("3 years from now", date.AddYears(3).ToRelativeTimeString(date)); }
public void TestMonthlyIntervalGetFireTimeAfter() { DateTimeOffset startCalendar = new DateTimeOffset(2005, 6, 1, 9, 30, 17, TimeSpan.Zero); CalendarIntervalTriggerImpl yearlyTrigger = new CalendarIntervalTriggerImpl(); yearlyTrigger.StartTimeUtc = startCalendar; yearlyTrigger.RepeatIntervalUnit = IntervalUnit.Month; yearlyTrigger.RepeatInterval = 5; // every five months DateTimeOffset targetCalendar = new DateTimeOffset(2005, 6, 1, 9, 30, 17, TimeSpan.Zero); targetCalendar = targetCalendar.AddMonths(25); // jump 25 five months (5 intervals) IList<DateTimeOffset> fireTimes = TriggerUtils.ComputeFireTimes(yearlyTrigger, null, 6); DateTimeOffset fifthTime = fireTimes[5]; // get the sixth fire time Assert.AreEqual(targetCalendar, fifthTime, "Month increment result not as expected."); }
/// <summary> /// Adds given <see cref="TimeSpan"/> to supplied <paramref name="originalValue"/> <see cref="DateTime"/> and returns resulting <see cref="DateTime"/> in the future. /// </summary> public static DateTimeOffset From(this FluentTimeSpan from, DateTimeOffset originalValue) { return originalValue.AddMonths(from.Months).AddYears(from.Years).Add(from.TimeSpan); }
public async Task GetTransactionsInDateRange() { IHttpClientWrapper httpClient = this.GetMockHttpClient("DateRangeTransactions.json", HttpStatusCode.OK, HttpMethod.Post, "connect/get"); IPlaidClient testClient = this.GetPlaidClient(httpClient); DateTimeOffset startDate = new DateTimeOffset(2014, 4, 1, 0, 0, 0, TimeSpan.Zero); DateTimeOffset endDate = startDate.AddMonths(1); TransactionResult result = await testClient.GetTransactionsAsync(new AccessToken("test_wells"), null, null, startDate, endDate); Assert.IsNotNull(result); Assert.IsFalse(result.IsError); Assert.IsNotNull(result.Accounts); Assert.IsNotNull(result.Transactions); Assert.AreEqual(4, result.Accounts.Count); Assert.AreEqual(5, result.Transactions.Count); foreach (Transaction t in result.Transactions) { Assert.IsTrue(t.Date > startDate); Assert.IsTrue(t.Date < endDate); } }
/// <summary> /// Creates the month range. /// </summary> /// <param name="current">The current</param> /// <returns>Set of days</returns> public static DateRange CreateMonthRange(DateTimeOffset current) { DateTimeOffset start = new DateTimeOffset(current.Year, current.Month, 1, 0, 0, 0, 0, TimeSpan.Zero); DateTimeOffset end = start.AddMonths(1).AddMilliseconds(-1); return new DateRange(start, end); }
internal void ResetByDate() { var rResetState = false; var rNow = DateTimeOffset.Now.ToOffset(TimeZoneOffset); if (!UpdateTime.HasValue) Current = 0; else { var rUpdateTime = UpdateTime.Value; DateTimeOffset rResetTime; switch (Type) { case QuestType.Daily: case QuestType.Special1: case QuestType.Special2: rResetTime = new DateTimeOffset(rNow.Year, rNow.Month, rNow.Day, 5, 0, 0, TimeZoneOffset); if (rNow.Hour < 5) rResetTime -= TimeSpan.FromDays(1.0); rResetState = rUpdateTime < rResetTime; break; case QuestType.Weekly: var rOffset = rNow.DayOfWeek - DayOfWeek.Monday; if (rOffset < 0) rOffset += 7; rResetTime = rNow.AddDays(-1 * rOffset) - rNow.TimeOfDay + ResetHour; rResetState = rUpdateTime < rResetTime; break; case QuestType.Monthly: rResetTime = new DateTimeOffset(rNow.Year, rNow.Month, 1, 5, 0, 0, TimeZoneOffset); if (rNow.Hour < 5) rResetTime = rResetTime.AddMonths(-1); rResetState = rUpdateTime < rResetTime; break; } } if (rResetState) { DebugUtil.Log(string.Format("任务 {0}: 被重置 原时间={1}", ID, UpdateTime.Value)); StateInternal = QuestState.None; CurrentInternal = 0; UpdateTime = rNow; RecordManager.Instance.Quest.UpdateProgress(this); RecordManager.Instance.Quest.UpdateStatus(this); } }
public static void AddMonths(DateTimeOffset dateTimeOffset, int months, DateTimeOffset expected) { Assert.Equal(expected, dateTimeOffset.AddMonths(months)); }