public List <Announcement> GetAnnouncements() { JArray arr = JObject.Parse(Request("/SchoolNotices"))["SchoolNotices"].ToObject <JArray>(); List <Announcement> res = new List <Announcement>(); try { for (int i = 0; i < arr.Count; i++) { JObject announcementObject = arr[i].ToObject <JObject>(); string id = announcementObject.GetValue("Id").ToString(); LocalDate start = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Parse(announcementObject.GetValue("StartDate").ToString()).Value; LocalDate end = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Parse(announcementObject.GetValue("EndDate").ToString()).Value; string subject = announcementObject.GetValue("Subject").ToString(); string content = announcementObject.GetValue("Content").ToString(); string authorId = announcementObject.SelectToken("AddedBy").ToObject <JObject>().GetValue("Id").ToString(); Announcement a = new Announcement(id, start, end, subject, content, authorId); res.Add(a); } announcements = res; return(res); } catch (Exception ex) { Log("failed to parse response (announcements)"); Log(ex.Message); throw ex; } }
public List <Attendance> GetAttendances() { JArray arr = JObject.Parse(Request("/Attendances"))["Attendances"].ToObject <JArray>(); List <Attendance> Attendances = new List <Attendance>(); try { for (int i = 0; i < arr.Count; i++) { JObject attendanceObject = arr[i].ToObject <JObject>(); string id = attendanceObject.GetValue("Id").ToString(); string lessonId = attendanceObject.SelectToken("Lesson").ToObject <JObject>().GetValue("Id").ToString(); // trip LocalDate date = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Parse(attendanceObject.GetValue("Date").ToString()).Value; LocalDateTime addDate = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss").Parse(attendanceObject.GetValue("AddDate").ToString()).Value; int lessonNumber = int.Parse(attendanceObject.GetValue("LessonNo").ToString()); int semesterNumber = int.Parse(attendanceObject.GetValue("Semester").ToString()); string typeId = attendanceObject.SelectToken("Type").ToObject <JObject>().GetValue("Id").ToString(); string authorId = attendanceObject.SelectToken("AddedBy").ToObject <JObject>().GetValue("Id").ToString(); Attendance attendance = new Attendance(id, lessonId, date, addDate, lessonNumber, semesterNumber, typeId, authorId); Attendances.Add(attendance); } attendances = Attendances; return(Attendances); } catch (Exception ex) { Log("failed to parse response (attendances)"); Log(ex.Message); throw ex; } }
public static void AddCustomSerialisationSettings(this JsonSerializerSettings jsonSerializerSettings) { var nodaTimeLocalDatePatternConverter = LocalDatePattern.CreateWithInvariantCulture("dd-MM-yyyy"); jsonSerializerSettings.Converters.Add(new NodaPatternConverter <LocalDate>(nodaTimeLocalDatePatternConverter)); jsonSerializerSettings.DateParseHandling = DateParseHandling.None; }
public ChangeFeedController(IClock clock) { _clock = clock ?? throw new ArgumentNullException(nameof(clock)); _localTimeZone = DateTimeZoneProviders.Tzdb["Europe/Brussels"]; _localMonthPattern = LocalDatePattern.Create("MMM", new CultureInfo("nl-BE")); _localTimeOfDayPattern = LocalTimePattern.CreateWithInvariantCulture("HH':'mm"); }
public static bool ParseDate(this string text, DateTimeZone zone, string cultureTab, bool longFormat, out Instant result) { var rc = false; result = InstantError; if ((zone != null) && (String.IsNullOrEmpty(cultureTab) == false)) { try { var culture = MxCultureInfo.Instance.GetCultureInfo(cultureTab); if (culture != null) { var parseResult = LocalDatePattern.Create(MxCultureInfo.GetFormatSpecifier(MxCultureInfo.FormatType.Date, longFormat), MxCultureInfo.Instance.GetCultureInfo(cultureTab)).Parse(text); if (parseResult.Success) { var instant = parseResult.Value.AtMidnight().InZoneStrictly(zone).ToInstant(); var local = instant.InZone(zone).LocalDateTime; if (zone.IsDaylightSavingsTime(instant)) { local = local.PlusSeconds(zone.GetZoneInterval(instant).Savings.Seconds); } result = local.InZoneStrictly(zone).ToInstant(); rc = true; } } } catch (Exception) { //ignore } } return(rc); }
public Option <IEnumerable <FoodItem> > Fetch(LocalDate forDate) { var urlForDate = UrlForDate(forDate); var reportsPage = _context.OpenAsync(urlForDate).Result; reportsPage.WaitForReadyAsync().Wait(TimeSpan.FromSeconds(5)); _logger.LogDebug($"fetching data from {urlForDate}"); _logger.LogTrace(reportsPage.ToHtml()); var datePattern = LocalDatePattern.CreateWithInvariantCulture("MMMM d, yyyy"); var dateRaw = reportsPage.QuerySelector <IHtmlHeadingElement>(Selectors.DateHeader).TextContent; var parsed = datePattern.Parse(dateRaw); if (parsed.Success) { var foodTable = reportsPage.QuerySelector <IHtmlTableElement>(Selectors.FoodTable); if (foodTable == null) { _logger.LogWarning($"skipping {forDate}. No food table found (table: {Selectors.FoodTable})"); return(None); } return(Some(FoodTableParser.ParseTable(foodTable, parsed.Value, _loggerFactory.CreateLogger(nameof(FoodTableParser))))); } _logger.LogWarning($"skipping {forDate}. couldn't parse date text: {dateRaw}"); return(None); }
public static bool ParseProperty(Type type, string value, [NotNullWhen(returnValue: true)] out object?parsedValue) { if (type == typeof(DateTime) || type == typeof(DateTime?)) { parsedValue = DateTime.Parse(value); return(true); } if (type == typeof(ZonedDateTime) || type == typeof(ZonedDateTime?)) { parsedValue = LocalDateTimePattern.CreateWithInvariantCulture(DATETIME_PATTERN).Parse(value).GetValueOrThrow().InUtc(); return(true); } if (type == typeof(LocalDateTime) || type == typeof(LocalDateTime?)) { parsedValue = LocalDateTimePattern.CreateWithInvariantCulture(DATETIME_PATTERN).Parse(value).GetValueOrThrow(); return(true); } if (type == typeof(LocalDate) || type == typeof(LocalDate?)) { parsedValue = LocalDatePattern.CreateWithInvariantCulture(DATE_PATTERN).Parse(value).GetValueOrThrow(); return(true); } if (type == typeof(LocalTime) || type == typeof(LocalTime?)) { parsedValue = LocalTimePattern.CreateWithInvariantCulture(TIME_PATTERN).Parse(value).GetValueOrThrow(); return(true); } parsedValue = null; return(false); }
public List <Event> GetEvents() { JArray arr = JObject.Parse(Request("/HomeWorks"))["HomeWorks"].ToObject <JArray>(); List <Event> Events = new List <Event>(); try { for (int i = 0; i < arr.Count; i++) { JObject eventObject = arr[i].ToObject <JObject>(); string id = eventObject.GetValue("Id").ToString(); string description = eventObject.GetValue("Content").ToString(); LocalDate date = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Parse(eventObject.GetValue("Date").ToString()).Value; string eventCategoryId = eventObject.SelectToken("Category").ToObject <JObject>().GetValue("Id").ToString(); int lessonNumber = int.Parse(eventObject.GetValue("LessonNo").ToString()); string authorId = eventObject.SelectToken("CreatedBy").ToObject <JObject>().GetValue("Id").ToString(); LocalDateTime addDate = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss").Parse(eventObject.GetValue("AddDate").ToString()).Value; Event e = new Event(id, description, date, eventCategoryId, lessonNumber, authorId, addDate); Events.Add(e); } this.events = Events; return(Events); } catch (Exception ex) { Log("failed to parse response (events)"); Log(ex.Message); throw ex; } }
private void AssertBclNodaEquality(CultureInfo culture, string patternText) { // The BCL never seems to use abbreviated month genitive names. // I think it's reasonable that we do. Hmm. // See https://github.com/nodatime/nodatime/issues/377 if (patternText.Contains("MMM") && !patternText.Contains("MMMM") && culture.DateTimeFormat.AbbreviatedMonthGenitiveNames[SampleLocalDate.Month - 1] != culture.DateTimeFormat.AbbreviatedMonthNames[SampleLocalDate.Month - 1]) { return; } var pattern = LocalDatePattern.Create(patternText, culture); var calendarSystem = BclCalendars.CalendarSystemForCalendar(culture.Calendar); if (calendarSystem == null) { // We can't map this calendar system correctly yet; the test would be invalid. return; } var sampleDateInCalendar = SampleLocalDate.WithCalendar(calendarSystem); // To construct a DateTime, we need a time... let's give a non-midnight one to catch // any unexpected uses of time within the date patterns. DateTime sampleDateTime = (SampleLocalDate + new LocalTime(2, 3, 5)).ToDateTimeUnspecified(); Assert.AreEqual(sampleDateTime.ToString(patternText, culture), pattern.Format(sampleDateInCalendar)); }
public DateFormatSpecification(string format) { if (format == null) { throw new ArgumentNullException(nameof(format)); } _pattern = LocalDatePattern.CreateWithInvariantCulture(format); }
static bool IsCorrectInputFile(FileEntry file, LocalDate date) { var isoParsed = LocalDatePattern.Iso.Parse(file.NameWithoutExtension); var yearDayParsed = LocalDatePattern.Create("uuuu-dd", CultureInfo.InvariantCulture, date).Parse(file.NameWithoutExtension); return(file.NameWithoutExtension.Equals($"day-{date.Day}", StringComparison.OrdinalIgnoreCase) || file.NameWithoutExtension.Equals($"day-{date.Year}-{date.Day}") || isoParsed.Success && isoParsed.Value == date || yearDayParsed.Success && yearDayParsed.Value == date); }
public void Format_NoValidPattern() { var pattern = new CompositePatternBuilder <LocalDate> { { LocalDatePattern.Iso, _ => false }, { LocalDatePattern.CreateWithInvariantCulture("yyyy"), _ => false }, }.Build(); Assert.Throws <FormatException>(() => pattern.Format(new LocalDate(2017, 1, 1))); }
static void Main() { var persianCalendar = CalendarSystem.GetPersianCalendar(); var pattern = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd") .WithTemplateValue(new LocalDate(1393, 1, 1, persianCalendar)); LocalDate result = pattern.Parse("1393-02-29").Value; DateTime dateTime = result.AtMidnight().ToDateTimeUnspecified(); Console.WriteLine(dateTime); // 19th May 2014 (Gregorian) }
public void MonthsBetween(string startText, int expectedMonths, string endText) { var civil = CalendarSystem.HebrewCivil; var pattern = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd") .WithTemplateValue(new LocalDate(5774, 1, 1, civil)); // Sample value in 2014 ISO var start = pattern.Parse(startText).Value; var end = pattern.Parse(endText).Value; Assert.AreEqual(expectedMonths, Period.Between(start, end, PeriodUnits.Months).Months); }
public void AddMonths_MonthsBetween(string startText, int months, string expectedEndText) { var civil = CalendarSystem.HebrewCivil; var pattern = LocalDatePattern.CreateWithInvariantCulture("uuuu-MM-dd") .WithTemplateValue(new LocalDate(5774, 1, 1, civil)); // Sample value in 2014 ISO var start = pattern.Parse(startText).Value; var expectedEnd = pattern.Parse(expectedEndText).Value; Assert.AreEqual(expectedEnd, start.PlusMonths(months)); }
public void Parse() { var pattern = new CompositePatternBuilder <LocalDate> { { LocalDatePattern.Iso, _ => true }, { LocalDatePattern.CreateWithInvariantCulture("yyyy"), _ => false }, }.Build(); Assert.IsTrue(pattern.Parse("2017-03-20").Success); Assert.IsFalse(pattern.Parse("2017-03").Success); Assert.IsTrue(pattern.Parse("2017").Success); }
public ConveyancingMatter MapFromActionstepTypes( GetActionResponse actionResponse, ListActionParticipantsResponse participantsResponse, ListDataCollectionRecordValuesResponse dataCollectionsResponse) { if (actionResponse is null) { throw new ArgumentNullException(nameof(actionResponse)); } var wCAConveyancingMatter = new ConveyancingMatter(); var action = actionResponse.Action; wCAConveyancingMatter.Id = action.Id; wCAConveyancingMatter.Name = action.Name; wCAConveyancingMatter.ActionType = actionResponse.ActionTypeName; wCAConveyancingMatter.FileReference = action.Reference; wCAConveyancingMatter.Conveyancers.AddRange(GetParticipants(participantsResponse, "Conveyancer")); wCAConveyancingMatter.Buyers.AddRange(GetParticipants(participantsResponse, "Buyer")); wCAConveyancingMatter.IncomingBanks.AddRange(GetParticipants(participantsResponse, "Bank_Incoming")); wCAConveyancingMatter.OthersideSolicitor.AddRange(GetParticipants(participantsResponse, "Otherside_Solicitor")); wCAConveyancingMatter.OthersideSolicitorPrimaryContact.AddRange(GetParticipants(participantsResponse, "Otherside_Solicitor_Primary_Contact")); wCAConveyancingMatter.PropertyDetails = new PropertyDetails { TitleReference = dataCollectionsResponse?["property", "titleref"], LotNo = dataCollectionsResponse["property", "lotno"] }; ConveyancingType conveyancingType; var isConveyancingTypeParseSuccess = Enum.TryParse <ConveyancingType>(dataCollectionsResponse["convdet", "ConveyType"], out conveyancingType); if (!isConveyancingTypeParseSuccess) { conveyancingType = ConveyancingType.None; } wCAConveyancingMatter.ConveyancingType = conveyancingType; var stringSettlementDate = dataCollectionsResponse["keydates", "smtdateonly"]; if (!String.IsNullOrEmpty(stringSettlementDate)) { var pattern = LocalDatePattern.Create("yyyy-MM-dd", CultureInfo.InvariantCulture); wCAConveyancingMatter.SettlementDate = pattern.Parse(stringSettlementDate).Value; } wCAConveyancingMatter.SettlementBookingTime = dataCollectionsResponse["convdet", "smttime"]; return(wCAConveyancingMatter); }
public void Enumerators() { var pattern1 = LocalDatePattern.Iso; var pattern2 = LocalDatePattern.CreateWithInvariantCulture("yyyy"); var builder = new CompositePatternBuilder <LocalDate> { { pattern1, _ => true }, { pattern2, _ => false }, }; CollectionAssert.AreEqual(new[] { pattern1, pattern2 }, builder.ToList()); CollectionAssert.AreEqual(new[] { pattern1, pattern2 }, builder.OfType <LocalDatePattern>().ToList()); }
public ServiceProvider BuildServiceProvider() { var services = new ServiceCollection(); this.ConfigureExternalServices(services); services.AddLogging(builder => builder.AddSerilog( new LoggerConfiguration() .Destructure.ByTransforming <LocalDate>(d => LocalDatePattern.CreateWithCurrentCulture("yyyy-MM-dd").Format(d)) .MinimumLevel.Debug() .Enrich.FromLogContext() .WriteTo.Console(new CompactJsonFormatter()) .CreateLogger(), dispose: true)); services.AddScoped <IEmailProvider, EmailProvider>(); services.AddScoped <IDatabaseProvider, DatabaseProvider>(); services.AddScoped <IIdentityProvider, IdentityProvider>(); services.AddScoped <INotificationProvider, NotificationProvider>(); services.AddScoped <IStorageProvider, StorageProvider>(); services.AddScoped <IAllocationCreator, AllocationCreator>(); services.AddScoped <AllocationNotifier>(); services.AddScoped <IBankHolidayRepository, BankHolidayRepository>(); services.AddScoped <IConfigurationRepository, ConfigurationRepository>(); services.AddScoped <IDateCalculator, DateCalculator>(); services.AddScoped <IEmailRepository, EmailRepository>(); services.AddScoped <INotificationRepository, NotificationRepository>(); services.AddScoped <Random>(); services.AddScoped <IRequestRepository, RequestRepository>(); services.AddScoped <IRequestSorter, RequestSorter>(); services.AddScoped <RequestUpdater>(); services.AddScoped <IReservationRepository, ReservationRepository>(); services.AddScoped <IScheduleRepository, ScheduleRepository>(); services.AddScoped <ScheduledTaskRunner>(); services.AddScoped <TriggerManager>(); services.AddScoped <ITriggerRepository, TriggerRepository>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <IScheduledTask, DailyNotification>(); services.AddScoped <IScheduledTask, RequestReminder>(); services.AddScoped <IScheduledTask, ReservationReminder>(); services.AddScoped <IScheduledTask, SoftInterruptionUpdater>(); services.AddScoped <IScheduledTask, WeeklyNotification>(); return(services.BuildServiceProvider()); }
public void CreateWithCurrentCulture() { var date = new LocalDate(2017, 8, 23); using (CultureSaver.SetCultures(Cultures.FrFr)) { var pattern = LocalDatePattern.CreateWithCurrentCulture("d"); Assert.AreEqual("23/08/2017", pattern.Format(date)); } using (CultureSaver.SetCultures(Cultures.FrCa)) { var pattern = LocalDatePattern.CreateWithCurrentCulture("d"); Assert.AreEqual("2017-08-23", pattern.Format(date)); } }
public static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .Destructure.ByTransforming <LocalDate>(d => LocalDatePattern.CreateWithCurrentCulture("yyyy-MM-dd").Format(d)) .MinimumLevel.Debug() .MinimumLevel.Override("Parking.Api.Authentication.DefaultAuthenticationHandler", LogEventLevel.Information) .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Console(new CompactJsonFormatter()) .CreateLogger(); CreateHostBuilder(args).Build().Run(); }
public IActionResult OnPostSelectAll([FromQuery] int?year, [FromQuery] int?month, [FromQuery] int?day) { if (!year.HasValue || !month.HasValue || !day.HasValue) { return(RedirectToPage("Index", new { year, month, day })); } var pageResult = PageResult(year.Value, month.Value, day.Value); SelectedDates.Clear(); foreach (var date in SelectedDate.ToYearMonth().ToDateInterval()) { SelectedDates.Add(LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Format(date)); } return(pageResult); }
public List <Grade> GetGrades() { JArray arr = JObject.Parse(Request("/Grades"))["Grades"].ToObject <JArray>(); List <Grade> Grades = new List <Grade>(); try { for (int i = 0; i < arr.Count; i++) { JObject gradeObject = arr[i].ToObject <JObject>(); string id = gradeObject.GetValue("Id").ToString(); string lessonId = gradeObject.SelectToken("Lesson").ToObject <JObject>().GetValue("Id").ToString(); string subjectId = gradeObject.SelectToken("Subject").ToObject <JObject>().GetValue("Id").ToString(); string categoryId = gradeObject.SelectToken("Category").ToObject <JObject>().GetValue("Id").ToString(); string authorId = gradeObject.SelectToken("AddedBy").ToObject <JObject>().GetValue("Id").ToString(); string grade = gradeObject.GetValue("Grade").ToString(); LocalDate date = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Parse(gradeObject.GetValue("Date").ToString()).Value; LocalDateTime addDate = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss").Parse(gradeObject.GetValue("AddDate").ToString()).Value; int semesterNumber = int.Parse(gradeObject.GetValue("Semester").ToString()); bool isConstituent = bool.Parse(gradeObject.GetValue("IsConstituent").ToString()); bool isSemesterGrade = bool.Parse(gradeObject.GetValue("IsSemester").ToString()); bool isSemesterProposition = bool.Parse(gradeObject.GetValue("IsSemesterProposition").ToString()); bool isFinalGrade = bool.Parse(gradeObject.GetValue("IsFinal").ToString()); bool isFinalProposition = bool.Parse(gradeObject.GetValue("IsFinalProposition").ToString()); string gradeCommentId; if (gradeObject.Property("Comments") != null) { gradeCommentId = gradeObject.SelectToken("Comments").ToObject <JArray>()[0].ToObject <JObject>().GetValue("Id").ToString(); } else { gradeCommentId = String.Empty; } Grade g = new Grade(id, lessonId, subjectId, categoryId, authorId, grade, date, addDate, semesterNumber, isConstituent, isSemesterGrade, isSemesterProposition, isFinalGrade, isFinalProposition, gradeCommentId); Grades.Add(g); } grades = Grades; return(Grades); } catch (Exception ex) { Log("failed to parse response (grades)"); Log(ex.Message); throw ex; } }
public static IList <Transaction> ReadDataxCsv(string file) { var datePattern = LocalDatePattern.CreateWithInvariantCulture("dd.MM.yyyy"); return(File .ReadAllLines(file) .Skip(1) .Select(line => line.Split(';')) .Select(elems => new Transaction { Description = elems[5].Replace("\"", ""), Amount = ParseAmount(elems[6]) - ParseAmount(elems[7]), TransactionDate = datePattern.Parse(elems[2].Replace("\"", "")).Value }).ToArray()); }
[TestCase("5400-09-30", 2, "5402-09-30")] // No truncation in Kislev (both 5503 and 5504 are long) public void SetYear(string startText, int years, string expectedEndText) { var civil = CalendarSystem.HebrewCivil; var scriptural = CalendarSystem.HebrewScriptural; var pattern = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd") .WithTemplateValue(new LocalDate(5774, 1, 1, scriptural)); // Sample value in 2014 ISO var start = pattern.Parse(startText).Value; var expectedEnd = pattern.Parse(expectedEndText).Value; Assert.AreEqual(expectedEnd, start.PlusYears(years)); // Check civil as well... the date should be the same (year, month, day) even though // the numbering is different. Assert.AreEqual(expectedEnd.WithCalendar(civil), start.WithCalendar(civil).PlusYears(years)); }
public static LocalDate?ParseDate(string str, bool allowNullYear = false) { // NodaTime can't parse constructs like "1st" and "2nd" so we quietly replace those away // Gotta make sure to do the regex otherwise we'll catch things like the "st" in "August" too str = Regex.Replace(str, "(\\d+)(st|nd|rd|th)", "$1"); var patterns = new[] { "MMM d yyyy", // Jan 1 2019 "MMM d, yyyy", // Jan 1, 2019 "MMMM d yyyy", // January 1 2019 "MMMM d, yyyy", // January 1, 2019 "yyyy-MM-dd", // 2019-01-01 "yyyy MM dd", // 2019 01 01 "yyyy/MM/dd" // 2019/01/01 }.ToList(); if (allowNullYear) { patterns.AddRange(new[] { "MMM d", // Jan 1 "MMMM d", // January 1 "MM-dd", // 01-01 "MM dd", // 01 01 "MM/dd" // 01/01 }); } // Giving a template value so year will be parsed as 0004 if not present // This means we can later disambiguate whether a null year was given // We use the basis year 0004 (rather than, say, 0001) because 0004 is a leap year in the Gregorian calendar // which means the date "Feb 29, 0004" is a valid date. 0001 is still accepted as a null year for legacy reasons. // TODO: should we be using invariant culture here? foreach (var pattern in patterns.Select(p => LocalDatePattern.CreateWithInvariantCulture(p).WithTemplateValue(new LocalDate(0004, 1, 1)))) { var result = pattern.Parse(str); if (result.Success) { return(result.Value); } } return(null); }
private static void CalendarTest(IGTFSFeed feed) { LocalDatePattern ptn = LocalDatePattern.CreateWithInvariantCulture("ddd uuuu-MM-dd"); foreach ((Calendar Cal, IEnumerable <CalendarDate> CalDates)cal in feed.Calendars) { Console.WriteLine($"Calendar: {cal.Cal.ID}"); Console.WriteLine($"Provides service on: {DayMasks.Get(cal.Cal.Mask)}"); Console.WriteLine($"Active {ptn.Format(cal.Cal.StartDate)} through {ptn.Format(cal.Cal.EndDate)}"); Console.WriteLine("Exceptions:"); foreach (CalendarDate date in cal.CalDates) { Console.WriteLine($" {ptn.Format(date.Date)}: {date.ExceptionType}"); } Console.WriteLine(); } }
public IActionResult OnGet([FromQuery] int year, [FromQuery] int month, [FromQuery] int day) { if (!ModelState.IsValid) { return(RedirectToPage("Index", new { year, month, day })); } StartTime = "09:00"; DurationMinutesForEachSlot = 30; CountOfSlotForEachSlot = 1; CountOfSlotsToCreate = 1; if (!SelectedDates.Any()) { SelectedDates.Add(LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Format(SelectedDate)); } return(PageResult(year, month, day)); }
private void AssertBclNodaEquality(CultureInfo culture, string patternText) { var pattern = LocalDatePattern.Create(patternText, culture); var calendarSystem = CalendarSystemForCalendar(culture.Calendar); if (calendarSystem == null) { // We can't map this calendar system correctly yet; the test would be invalid. return; } var sampleDateInCalendar = SampleLocalDate.WithCalendar(calendarSystem); // To construct a DateTime, we need a time... let's give a non-midnight one to catch // any unexpected uses of time within the date patterns. DateTime sampleDateTime = (SampleLocalDate + new LocalTime(2, 3, 5)).ToDateTimeUnspecified(); Assert.AreEqual(sampleDateTime.ToString(patternText, culture), pattern.Format(sampleDateInCalendar)); }
public static void Main() { // Providing the sample date to the pattern tells it which // calendar to use. // Noda Time 2.0 uses a property instead of a method. // var calendar = CalendarSystem.Persian; // 2.0+ var calendar = CalendarSystem.GetPersianCalendar(); // 1.x LocalDate sampleDate = new LocalDate(1392, 10, 12, calendar); var pattern = LocalDatePattern.Create( "yyyy/M/d", CultureInfo.InvariantCulture, sampleDate); string text = "1393/04/31"; ParseResult <LocalDate> parseResult = pattern.Parse(text); if (parseResult.Success) { LocalDate date = parseResult.Value; // Use the date } }