/// <summary> /// Get a <see cref="DateOnly"/> in the future between <paramref name="refDate"/> and <paramref name="yearsToGoForward"/>. /// </summary> /// <param name="yearsToGoForward">Years to go forward from <paramref name="refDate"/>. Default is 1 year.</param> /// <param name="refDate">The date to start calculations. Default is from <see cref="DateTime.Now"/>.</param> public DateOnly FutureDateOnly(int yearsToGoForward = 1, DateOnly?refDate = null) { var start = refDate ?? DateOnly.FromDateTime(SystemClock()); var maxForward = start.AddYears(yearsToGoForward); return(BetweenDateOnly(start, maxForward)); }
/// <summary> /// Get a random <see cref="DateOnly"/> within the last few days. /// </summary> /// <param name="days">Number of days to go back.</param> /// <param name="refDate">The date to start calculations. Default is from <see cref="DateTime.Now"/>.</param> public DateOnly RecentDateOnly(int days = 1, DateOnly?refDate = null) { var start = refDate ?? DateOnly.FromDateTime(SystemClock()); var maxBehind = start.AddDays(-days); return(BetweenDateOnly(maxBehind, start)); }
/// <summary> /// Get a <see cref="DateOnly"/> that will happen soon. /// </summary> /// <param name="days">A date no more than <paramref name="days"/> ahead.</param> /// <param name="refDate">The date to start calculations. Default is from <see cref="DateTime.Now"/>.</param> public DateOnly SoonDateOnly(int days = 1, DateOnly?refDate = null) { var start = refDate ?? DateOnly.FromDateTime(SystemClock()); var maxForward = start.AddDays(days); return(BetweenDateOnly(start, maxForward)); }
public async Task OnGetAsync( DateTime?fromDate, DateTime?toDate, Guid[] themes, string?filterName, bool?combineThemes, int?pageNo) { CombineThemes = combineThemes ?? false; Filters = new RecordsFilter { PageSize = _pageSize, FromDate = fromDate == null ? null : DateOnly.FromDateTime(fromDate.Value), ToDate = toDate == null ? null : DateOnly.FromDateTime(toDate.Value), FilterName = filterName?.Trim(), PageNo = (pageNo ?? 1) - 1, CombineThemes = CombineThemes }; if (themes != null && themes.Length > 0) { Filters.AddThemeId(themes); SelectedThemes = themes; } var recordsCount = await _searchRecordsService.GetRecordsCount(Filters); Pages = PagesInfo.GetPagesInfo(recordsCount, Filters.PageNo + 1, _pageSize, 10); Records = await _searchRecordsService.GetRecordsList(Filters); AllScopes = await _scopesSvc.GetScopes(); }
public override DateOnly?ReadJson(JsonReader reader, Type objectType, DateOnly?existingValue, bool hasExistingValue, JsonSerializer serializer) { if (reader.Value == null) { return(null); } if (reader.Value.GetType() == typeof(string)) { Regex dateOnlyRegex = new(@"\d{4}-\d{1,2}-\d{1,2}"); Match match = dateOnlyRegex.Match((string)reader.Value); if (match.Success && match.Groups.Count == 1) { return(DateOnly.ParseExact(match.Groups[0].Value, DateFormat, CultureInfo.InvariantCulture)); } } if (reader.Value.GetType() == typeof(DateTime)) { return(DateOnly.FromDateTime((DateTime)reader.Value)); } return(null); }
public async Task <IEnumerable <WeatherForecast> > Get() { using var response = await _downstreamWebApi.CallWebApiForUserAsync("DownstreamApi").ConfigureAwait(false); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var apiResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false); // Do something } else { var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false); throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}"); } return(Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray()); }
public async Task GetRecordsList_ForDateAndTheme_ShouldReturnOnlyMatchedRecords() { var context = CreateContext(); Create_30Themes_20Records(context, GetNumberList(20), GetDatesListWithTwoSameDatesWeekAgo(20)); var(themeId1, recordsNamesForTheme1, themeId2, recordsNamesForTheme2) = BindRecordsWithThemes(context, ThemesTestDataSet.DatesAndThemesRec); var searchService = GetRecordsSearchService(context); var dateFrom = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(-10)); var dateTo = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(-5)); var filter = new RecordsFilter { FromDate = dateFrom, ToDate = dateTo }; filter.AddThemeId(themeId1); var list = context.Records.Where(r => r.Date >= dateFrom && r.Date <= dateTo); var result = await searchService.GetRecordsList(filter); result.Should().OnlyContain(rec => rec.Date >= dateFrom && rec.Date <= dateTo); result.Select(r => r.Name).Should().BeEquivalentTo(new string[] { "05", "07", "09", "10" }); //-------------------------------------------------// filter.AddThemeId(themeId2); filter.RemoveThemeId(themeId1); result = await searchService.GetRecordsList(filter); result.Select(r => r.Name).Should().BeEquivalentTo(new string[] { "05" }); }
public void ToCollection_DateOnlyColumn(string dataSourceName, DataSourceType mode) { var dataSource = DataSource(dataSourceName, mode); try { var uniqueKey = Guid.NewGuid().ToString(); var cust1 = new CustomerWithDate() { FullName = uniqueKey, State = "XX", BirthDay = DateOnly.FromDateTime(DateTime.Now) }; var cust2 = new CustomerWithDate() { FullName = uniqueKey, State = "XX", BirthDay = DateOnly.FromDateTime(DateTime.Now) }; var cust3 = new CustomerWithDate() { FullName = uniqueKey, State = "XX", BirthDay = DateOnly.FromDateTime(DateTime.Now) }; dataSource.Insert(CustomerTableName, cust1).Execute(); dataSource.Insert(CustomerTableName, cust2).Execute(); dataSource.Insert(CustomerTableName, cust3).Execute(); var lookup = dataSource.From(CustomerTableName, new { FullName = uniqueKey }).WithSorting("CustomerKey").ToCollection <CustomerWithDate>().Execute(); Assert.AreEqual(cust1.BirthDay, lookup[0].BirthDay); } finally { Release(dataSource); } }
public unsafe static void TestDateOnly() { var str = stackalloc char[20]; var span = new Span <char>(str, 20); var date = DateOnly.FromDateTime(DateTime.Today); var sw = Stopwatch.StartNew(); for (var i = 0; i < 1000000; ++i) { if (!date.TryFormat(span, out var length)) { throw new Exception(); } if (!DateOnly.TryParse(span.Slice(0, length), out date)) { throw new Exception(); } } sw.Stop(); Console.WriteLine("DateOnly自带转换耗时:" + sw.ElapsedMilliseconds.ToString()); sw.Restart(); for (var i = 0; i < 1000000; ++i) { if (!DateOnlyFormat.Singleton.TryFormat(date, span, out var length)) { throw new Exception(); } if (!DateOnlyFormat.Singleton.TryParse(span.Slice(0, length), out date)) { throw new Exception(); } } sw.Stop(); Console.WriteLine("Sunny库转换耗时:" + sw.ElapsedMilliseconds.ToString()); }
/// <summary> /// Get a <see cref="DateOnly"/> in the past between <paramref name="refDate"/> and <paramref name="yearsToGoBack"/>. /// </summary> /// <param name="yearsToGoBack">Years to go back from <paramref name="refDate"/>. Default is 1 year.</param> /// <param name="refDate">The date to start calculations. Default is from <see cref="DateTime.Now"/>.</param> public DateOnly PastDateOnly(int yearsToGoBack = 1, DateOnly?refDate = null) { var start = refDate ?? DateOnly.FromDateTime(SystemClock()); var maxBehind = start.AddYears(-yearsToGoBack); return(BetweenDateOnly(maxBehind, start)); }
public static void ComparisonsTest() { DateOnly dateOnly1 = DateOnly.FromDateTime(DateTime.Today); DateOnly dateOnly2 = DateOnly.FromDateTime(DateTime.Today); DateOnly dateOnly3 = dateOnly1.AddYears(-10); Assert.Equal(0, dateOnly1.CompareTo(dateOnly2)); Assert.True(dateOnly1.Equals(dateOnly2)); Assert.True(dateOnly1.Equals((object)dateOnly2)); Assert.Equal(0, dateOnly2.CompareTo(dateOnly1)); Assert.True(dateOnly2.Equals(dateOnly1)); Assert.True(dateOnly2.Equals((object)dateOnly1)); Assert.Equal(1, dateOnly1.CompareTo(dateOnly3)); Assert.False(dateOnly1.Equals(dateOnly3)); Assert.False(dateOnly1.Equals((object)dateOnly3)); Assert.Equal(-1, dateOnly3.CompareTo(dateOnly1)); Assert.False(dateOnly3.Equals(dateOnly1)); Assert.False(dateOnly3.Equals((object)dateOnly1)); Assert.Equal(0, dateOnly1.CompareTo((object)dateOnly2)); Assert.Equal(0, dateOnly2.CompareTo((object)dateOnly1)); Assert.Equal(1, dateOnly1.CompareTo((object)dateOnly3)); Assert.Equal(-1, dateOnly3.CompareTo((object)dateOnly1)); Assert.Equal(1, dateOnly1.CompareTo(null)); Assert.Throws <ArgumentException>(() => dateOnly1.CompareTo(new object())); Assert.False(dateOnly3.Equals(new object())); }
public async Task Registrar(TrabajadorRegisterViewModel model) { var negocio = new NegocioViewModel { IdNegocio = Guid.NewGuid().ToString(), Nombre = model.NombreNegocio, TipoNegocio = model.TipoNegocio }; await negocioRepository.Add(negocio); string contrasenaEncriptada = BCrypt.Net.BCrypt.HashPassword(model.Contrasena.Trim()); var trabajador = new Trabajador { Rut = model.Rut.Replace(".", "").Replace("-", "").Trim(), IdNegocio = negocio.IdNegocio.ToString(), IdRol = "1", Correo = model.Correo.Trim(), Contrasena = contrasenaEncriptada, Nombre = model.Nombre.Trim(), Apellido = model.Apellido?.Trim(), FechaNacimiento = DateOnly.FromDateTime(model.FechaNacimiento), Telefono = model.Telefono?.Trim() }; await Add(trabajador); }
public override void FormatValue(StringBuilder queryStringBuilder, object?value) { if (value == null || value is DBNull) { throw new ClickHouseException(ClickHouseErrorCodes.TypeNotSupported, $"The ClickHouse type \"{ComplexTypeName}\" does not allow null values"); } int days; if (value is DateOnly dateOnlyValue) { days = dateOnlyValue == default ? MinValue : dateOnlyValue.DayNumber - UnixEpoch.DayNumber; } else if (value is DateTime dateTimeValue) { days = dateTimeValue == default ? MinValue : DateOnly.FromDateTime(dateTimeValue).DayNumber - UnixEpoch.DayNumber; } else { throw new ClickHouseException(ClickHouseErrorCodes.TypeNotSupported, $"The type \"{value.GetType()}\" can't be converted to the ClickHouse type \"{ComplexTypeName}\"."); } if (days < MinValue || days > MaxValue) { throw new OverflowException("The value must be in range [1925-01-01, 2283-11-11]."); } queryStringBuilder.Append(days.ToString(CultureInfo.InvariantCulture)); }
public static void OAndRFormatsTest() { DateOnly dateOnly = DateOnly.FromDateTime(DateTime.Today); string formattedDate = dateOnly.ToString("o"); Assert.Equal(10, formattedDate.Length); Assert.Equal('-', formattedDate[4]); Assert.Equal('-', formattedDate[7]); DateOnly parsedDateOnly = DateOnly.Parse(formattedDate); Assert.Equal(dateOnly, parsedDateOnly); parsedDateOnly = DateOnly.Parse(formattedDate.AsSpan()); Assert.Equal(dateOnly, parsedDateOnly); parsedDateOnly = DateOnly.ParseExact(formattedDate, "O"); Assert.Equal(dateOnly, parsedDateOnly); parsedDateOnly = DateOnly.ParseExact(formattedDate.AsSpan(), "O".AsSpan()); Assert.Equal(dateOnly, parsedDateOnly); formattedDate = dateOnly.ToString("r"); Assert.Equal(16, formattedDate.Length); Assert.Equal(',', formattedDate[3]); Assert.Equal(' ', formattedDate[4]); Assert.Equal(' ', formattedDate[7]); Assert.Equal(' ', formattedDate[11]); parsedDateOnly = DateOnly.Parse(formattedDate); Assert.Equal(dateOnly, parsedDateOnly); parsedDateOnly = DateOnly.Parse(formattedDate.AsSpan()); Assert.Equal(dateOnly, parsedDateOnly); parsedDateOnly = DateOnly.ParseExact(formattedDate, "R"); Assert.Equal(dateOnly, parsedDateOnly); parsedDateOnly = DateOnly.ParseExact(formattedDate.AsSpan(), "R".AsSpan()); Assert.Equal(dateOnly, parsedDateOnly); }
public void ProjectionJobsWithDateTimeDateOnly() { using var store = GetDocumentStore(); { using var s = store.OpenSession(); s.Store(new DateAndTimeOnly() { TimeOnly = TimeOnly.MaxValue, DateOnly = new DateOnly(1947, 12, 21) }); s.Store(new DateAndTimeOnly()); s.SaveChanges(); } var today = DateOnly.FromDateTime(DateTime.Today); { using var s = store.OpenSession(); var q = s .Query <DateAndTimeOnly>() .Where(p => p.DateOnly != null) .Select(p => new DateAndTimeOnly { Age = (today.Year - p.DateOnly.Value.Year) }) .Single(); Assert.Equal(today.Year - 1947, q.Age); } }
/// <summary> /// 转换成日期类型 /// </summary> /// <param name="this"></param> /// <param name="value">失败时间</param> /// <returns></returns> public static DateOnly ToDateOnly(this string @this, DateOnly value) { if (string.IsNullOrWhiteSpace(@this)) { return(value); } return(DateTime.TryParse(@this, out var result) ? DateOnly.FromDateTime(result) : value); }
public static void GetHashCodeTest() { Assert.Equal(DateOnly.MinValue.DayNumber, DateOnly.MinValue.GetHashCode()); Assert.Equal(DateOnly.MaxValue.DayNumber, DateOnly.MaxValue.GetHashCode()); DateOnly dateOnly = DateOnly.FromDateTime(DateTime.Today); Assert.Equal(dateOnly.DayNumber, dateOnly.GetHashCode()); }
public void DateTimeFunctionsConvert() { Dump((NoteWithDateEntity n) => n.CreationTime.ToDateOnly()); Dump((NoteWithDateEntity n) => DateOnly.FromDateTime(n.CreationTime)); Dump((NoteWithDateEntity n) => n.CreationDate.ToDateTime()); Dump((NoteWithDateEntity n) => n.CreationDate.ToDateTime(TimeOnly.MaxValue)); }
public DateOnly RandomDate(DateTime rangeStart, DateTime rangeEnd) { TimeSpan span = rangeEnd - rangeStart; int randomMinutes = rnd.Next(0, (int)span.TotalMinutes); return(DateOnly.FromDateTime(rangeStart + TimeSpan.FromMinutes(randomMinutes))); }
public IReadOnlyCollection <Ppe> RemoveExpiredPpes() { var experied = Ppes.Where(epi => epi.Expiration < DateOnly.FromDateTime(DateTime.Now)); Ppes = Ppes.Where(epi => epi.Expiration >= DateOnly.FromDateTime(DateTime.Now)).ToList(); return(experied.ToList()); }
public async Task DocumentEndToEnd(IDocumentSerializer serializer) { var table = CloudStorageAccount.DevelopmentStorageAccount .CreateTableServiceClient() .GetTableClient(serializer.GetType().Name); await table.DeleteAsync(); await table.CreateAsync(); try { var repo = DocumentRepository.Create <DocumentEntity>(CloudStorageAccount.DevelopmentStorageAccount, table.Name, serializer: serializer); var partitionKey = "P" + Guid.NewGuid().ToString("N"); var rowKey = "R" + Guid.NewGuid().ToString("N"); var entity = await repo.PutAsync(new DocumentEntity { PartitionKey = partitionKey, RowKey = rowKey, Title = "Foo", }); entity.Title = "Bar"; await repo.PutAsync(entity); var saved = await repo.GetAsync(partitionKey, rowKey); Assert.NotNull(saved); Assert.Equal("Bar", saved !.Title); Assert.Equal(DateOnly.FromDateTime(DateTime.Today), saved.Date); var entities = new List <DocumentEntity>(); await foreach (var e in repo.EnumerateAsync(partitionKey)) { entities.Add(e); } Assert.Single(entities); await repo.DeleteAsync(saved); Assert.Null(await repo.GetAsync(partitionKey, rowKey)); await foreach (var _ in repo.EnumerateAsync(partitionKey)) { Assert.False(true, "Did not expect to find any entities"); } } finally { await table.DeleteAsync(); } }
public async Task <ActionResult <RecordsPageDto> > GetRecordsList( [FromQuery] DateTime?from, [FromQuery] DateTime?to, [FromQuery] string?name, [FromQuery] bool?combinedThemes, [FromQuery] Guid[]?themeId, [FromQuery] int?pageSize, [FromQuery] int?pageNo) { try { pageSize ??= 20; pageSize = pageSize > 100 ? 100 : pageSize; pageNo ??= 0; var filters = new RecordsFilter { CombineThemes = combinedThemes ?? false, PageSize = pageSize.Value, PageNo = pageNo.Value, FromDate = from.HasValue ? DateOnly.FromDateTime(from.Value) : null, ToDate = to.HasValue ? DateOnly.FromDateTime(to.Value) : null, FilterName = name }; if (themeId != null && themeId.Length > 0) { filters.AddThemeId(themeId); } var records = await _recordsSearchService.GetRecordsList(filters); int allCount = await _recordsSearchService.GetRecordsCount(filters); var pagesInfo = PagesInfo.GetPagesInfo(allCount, pageNo.Value, pageSize.Value); var dto = new RecordsPageDto { PagesInfo = pagesInfo, Records = records.Select(r => new RecordListItemDto { Date = r.Date, CreatedDate = r.CreateDate, ModifiedDate = r.ModifyDate, DisplayedName = r.GetRecordNameDisplay(), DisplayedText = r.GetRecordTextShort(), RecordId = r.Id }).ToList() }; return(Ok(dto)); } catch (ArgumentException exc) { return(BadRequest(exc.Message)); } }
public void Filter_SetDateFrom_ShouldCleareTime() { var recFilter = RecordsFilter.Empty; var date = DateOnly.FromDateTime(DateTime.UtcNow); recFilter.FromDate = date; Assert.AreEqual(recFilter.FromDate, date); }
private static DateOnly ConvertToDateOnly(DateTime?dateTime) { if (dateTime.HasValue) { return(DateOnly.FromDateTime(dateTime.Value)); } else { return(default);
/// <summary> /// Creates a new instance of this converter. /// </summary> public NullableDateOnlyConverter() : base( d => d == null ? null : new DateTime?(d.Value.ToDateTime(TimeOnly.MinValue)), d => d == null ? null : new DateOnly?(DateOnly.FromDateTime(d.Value))) { }
public void Filter_SetDateFromProperty_ShouldSet() { var filter = RecordsFilter.Empty; var date = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(-7)); filter.FromDate = date; Assert.AreEqual(filter.FromDate, date); filter.FromDate = null; Assert.IsNull(filter.FromDate); }
public IEnumerable <WeatherForecast> Get() { return(Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray()); }
public IndexWithDateTimeAndDateOnly() { Map = dates => from date in dates let x = date.DateTime select new IndexEntry() { Year = x.Value.Year, DateOnly = x == null ? null : DateOnly.FromDateTime(x.Value), DateTime = x.Value }; }
public IndexWithDateTimeAndDateOnly() { Map = dates => from date in dates let x = date.DateTime select new IndexEntry() { Year = x.Year, DateOnly = DateOnly.FromDateTime(x), DateTime = x }; }
public override DateOnly?Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TryGetDateTime(out var dt)) { return(DateOnly.FromDateTime(dt)); } ; var value = reader.GetString(); if (value == null) { return(default);