public Option <(FileInfo file, LocalDateTime exportTime, ContentType contentType)> GetLatestExportFile() { return(GetExportFiles() .OrderBy(s => s.Name) .Select(x => (file: x, parsed: _exportFilePattern.Parse(x.Name))) .Where(x => x.parsed.Success) .Select(x => (x.file, exportTime: x.parsed.Value, contentType: Output.XlsxContentType)) .LastOrDefault() .Then(Optional)); }
/// <summary> /// Constructor /// Sets up the default serialization for some basic types, which can /// be overwritten by the user. /// </summary> public TypeConverterSetup() { /* * Default type conversions */ this.RegisterTypeConverter <int, string>(x => x.ToString()); this.RegisterTypeConverter <string, int>(x => Convert.ToInt32(x)); this.RegisterTypeConverter <long, string>(x => x.ToString()); this.RegisterTypeConverter <string, long>(x => Convert.ToInt64(x)); this.RegisterTypeConverter <float, string>(x => x.ToString()); this.RegisterTypeConverter <string, float>(x => Convert.ToSingle(x)); this.RegisterTypeConverter <double, string>(x => x.ToString()); this.RegisterTypeConverter <string, double>(x => Convert.ToDouble(x)); this.RegisterTypeConverter <decimal, string>(x => x.ToString()); this.RegisterTypeConverter <string, decimal>(x => Convert.ToDecimal(x)); this.RegisterTypeConverter <LocalDate, string>(x => datePattern.Format(x)); this.RegisterTypeConverter <string, LocalDate>(x => datePattern.Parse(x).Value); this.RegisterTypeConverter <LocalDateTime, string>((x) => { return(dtPattern.Format(x)); }); this.RegisterTypeConverter <string, LocalDateTime>((x) => { return(dtPattern.Parse(x).Value); }); }
internal EarlyClose(JsonElement json) { var date = json.GetProperty("date").GetString(); DateTime = DateTimePattern.Parse(date).Value; Name = json.GetProperty("name").GetString(); }
internal EarlyClose(JsonElement json) { string date = json.GetProperty("date").GetString() ?? throw new InvalidDataException("Missing property: 'date'"); DateTime = DateTimePattern.Parse(date).Value; Name = json.GetProperty("name").GetString() ?? throw new InvalidDataException("Missing property: 'name'"); }
protected override void OnConfiguring(TypeConverterSetup typeConverterSetup, Configurator configurator) { typeConverterSetup .RegisterTypeConverter <LocalDateTime, string>((x) => { return(pattern.Format(x)); }) .RegisterTypeConverter <string, LocalDateTime>((x) => { return(pattern.Parse(x).Value); }); configurator .SetTransactionParallelism(1) .SetQueryParallelism(1) .EnableDurability(false); }
static void Main(string[] args) { //This is an attempt to make a birthday checker //User will enter DOB, program will compare that to current day //If the DOB indicates the person is 21 or, program will display VALID SALE //This is a test of concept //I just want to see if I can do it Console.Write("Enter DOB: "); string input = Console.ReadLine(); //get input LocalDateTimePattern pattern = LocalDateTimePattern.CreateWithInvariantCulture("MMddyy"); //set pattern for parsing from string ParseResult <LocalDateTime> parseResult = pattern.Parse(input); //parse string from input LocalDateTime dob = parseResult.Value; //returns value of parse result //date of birth set as variable 'dob' Instant today = SystemClock.Instance.Now; //gets current date from system clock var timeZone = DateTimeZoneProviders.Tzdb["US/Central"]; //gets US Central as Time zone ZonedDateTime zonedToday = today.InZone(timeZone); //converts instant variable to ZonedDateTime in Central Time LocalDateTime localToday = zonedToday.LocalDateTime; //Converts ZonedDateTime to LocalDateTime, suitable for Period //final, useable value for today set as variable 'localToday' Period agePeriod = Period.Between(dob, localToday); //gets amount of time between two dates long age = agePeriod.Years; //gets years component of period. Component Years takes long data type //this is the variable to use for age. We don't care about months, weeks, days, etc //Only LocalDateTime variables can use Period. Instant variable must be converted to LocalDateTime via ZonedDateTime if (age >= 21) //simple conditional. Does the date of birth put the person at or over 21 years old { Console.WriteLine($"VALID SALE ({age})"); } else { Console.WriteLine($"DENY SALE({age})"); } //I can do it }
static ZonedDateTime Parse(string text) { int gmtIndex = text.IndexOf(" GMT"); int zoneIndex = text.IndexOf(" ("); // TODO: Validation that these aren't -1 :) string localText = text.Substring(0, gmtIndex); string offsetText = text.Substring(gmtIndex, zoneIndex - gmtIndex); var localResult = LocalPattern.Parse(localText); var offsetResult = OffsetPattern.Parse(offsetText); // TODO: Validate that both are successful var fixedZone = DateTimeZone.ForOffset(offsetResult.Value); return(localResult.Value.InZoneStrictly(fixedZone)); }
public static LocalDateTime LocalDateTime(string value) => LocalDateTimePattern.Parse(value).Value;
private static void ParseEventTimestamps(string bodyString, string timezone, ref Event evt) { var tz = DateTimeZoneProviders.Tzdb.GetZoneOrNull(timezone); if (tz == null) { throw new InvalidTimeZoneException(); } var results = DateTimeRecognizer.RecognizeDateTime(bodyString, Culture.English); if (results.Count > 0 && results.Any(r => r.TypeName.StartsWith("datetimeV2"))) { var first = results .Where(r => r.Resolution != null) .SkipWhile(r => { var v = (IList <Dictionary <string, string> >)r.Resolution["values"]; var returnValue = v.Any(x => { try { return(x["value"] == "not resolved"); } catch (KeyNotFoundException) { return(false); } }); return(returnValue); }) .FirstOrDefault(); if (first == null) { throw new EventParseException(); } var resolutionValues = (IList <Dictionary <string, string> >)first.Resolution["values"]; var subType = first.TypeName.Split('.').Last(); if (subType == "date") { string timex = resolutionValues.Select(v => v["timex"]).FirstOrDefault(); string value = resolutionValues.Select(v => v["value"]).FirstOrDefault(); if (timex.StartsWith("XXXX-")) { value = value.Substring(4); value = string.Format("{0}{1}", DateTime.Now.Year, value); } LocalDateTime startDateTime = _dateOnlyPattern.Parse(value).Value; ZonedDateTime zonedStartDateTime = tz.AtLeniently(startDateTime); if (IsFuture(zonedStartDateTime.ToDateTimeOffset())) { evt.StartTimestamp = zonedStartDateTime.ToDateTimeOffset(); evt.EndTimestamp = zonedStartDateTime.ToDateTimeOffset().AddHours(1); } else { throw new DateTimeInPastException(); } } else if (subType.Contains("date") && !subType.Contains("range")) { string timex = resolutionValues.Select(v => v["timex"]).FirstOrDefault(); string value = resolutionValues.Select(v => v["value"]).FirstOrDefault(); if (timex.StartsWith("XXXX-")) { value = value.Substring(4); value = string.Format("{0}{1}", DateTime.Now.Year, value); } LocalDateTime startDateTime = _dateTimePattern.Parse(value).Value; ZonedDateTime zonedStartDateTime = tz.AtLeniently(startDateTime); if (IsFuture(zonedStartDateTime.ToDateTimeOffset())) { evt.StartTimestamp = zonedStartDateTime.ToDateTimeOffset(); evt.EndTimestamp = zonedStartDateTime.ToDateTimeOffset().AddHours(1); } else { throw new DateTimeInPastException(); } } else if (subType.Contains("date") && subType.Contains("range")) { string timex = resolutionValues.First()["timex"].TrimStart('(').TrimEnd(')'); string[] timexSplit = timex.Split(','); string fromString = resolutionValues.First()["start"]; string toString = resolutionValues.First()["end"]; if (timexSplit[0].StartsWith("XXXX-")) { fromString = fromString.Substring(4); fromString = string.Format("{0}{1}", DateTime.Now.Year, fromString); } Console.WriteLine(timexSplit.Length); if (timexSplit.Length > 1 && timexSplit[1].StartsWith("XXXX-")) { toString = toString.Substring(4); toString = string.Format("{0}{1}", DateTime.Now.Year, toString); } LocalDateTime from, to; if (fromString.Length == 10) { from = _dateOnlyPattern.Parse(fromString).Value; } else { from = _dateTimePattern.Parse(fromString).Value; } if (toString.Length == 10) { to = _dateOnlyPattern.Parse(toString).Value; } else { to = _dateTimePattern.Parse(toString).Value; } ZonedDateTime zonedFrom = tz.AtLeniently(from); ZonedDateTime zonedTo = tz.AtLeniently(to); if (IsFuture(zonedFrom.ToDateTimeOffset()) && IsFuture(zonedTo.ToDateTimeOffset())) { evt.StartTimestamp = zonedFrom.ToDateTimeOffset(); evt.EndTimestamp = zonedTo.ToDateTimeOffset(); if (IsEventEndBeforeStart(evt)) { throw new EventEndBeforeStartException(); } } else { throw new DateTimeInPastException(); } } else if (subType.Contains("time") && !subType.Contains("range")) { var clock = SystemClock.Instance; LocalDate today = clock.InZone(tz).GetCurrentDate(); string timeString = resolutionValues.Select(v => v["value"]).FirstOrDefault(); string dateTimeString = string.Format("{0} {1}", today.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), timeString); LocalDateTime startDateTime = _dateTimePattern.Parse(dateTimeString).Value; ZonedDateTime zonedStartDateTime = tz.AtLeniently(startDateTime); if (IsFuture(zonedStartDateTime.ToDateTimeOffset())) { evt.StartTimestamp = zonedStartDateTime.ToDateTimeOffset(); evt.EndTimestamp = zonedStartDateTime.ToDateTimeOffset().AddHours(1); } else { throw new DateTimeInPastException(); } } else if (subType.Contains("time") && subType.Contains("range")) { var clock = SystemClock.Instance; LocalDate today = clock.InZone(tz).GetCurrentDate(); string fromString = resolutionValues.First()["start"]; string toString = resolutionValues.First()["end"]; string fromDateTimeString = string.Format("{0} {1}", today.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), fromString); string toDateTimeString = string.Format("{0} {1}", today.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), toString); LocalDateTime startDateTime = _dateTimePattern.Parse(fromDateTimeString).Value; ZonedDateTime zonedStartDateTime = tz.AtLeniently(startDateTime); LocalDateTime endDateTime = _dateTimePattern.Parse(toDateTimeString).Value; ZonedDateTime zonedEndDateTime = tz.AtLeniently(endDateTime); if (IsFuture(zonedStartDateTime.ToDateTimeOffset()) && IsFuture(zonedEndDateTime.ToDateTimeOffset())) { evt.StartTimestamp = zonedStartDateTime.ToDateTimeOffset(); evt.EndTimestamp = zonedEndDateTime.ToDateTimeOffset(); if (IsEventEndBeforeStart(evt)) { throw new EventEndBeforeStartException(); } } else { throw new DateTimeInPastException(); } } else { throw new EventParseException(); } evt.Name = bodyString.RemoveCaseInsensitive(first.Text); } else { throw new EventParseException(); } }
public void ParseWithNumbersToSecond() { PatternWithNumbersToSecond.Parse("26/12/2009 10:08:30").GetValueOrThrow(); }
public void ParseLongMonthAndDay() { PatternWithLongMonthAndDay.Parse("Friday April 12 2013 20:28:42").GetValueOrThrow(); }
private object ParseImpl <T>(string s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } var type = typeof(T); if (type == typeof(string)) { return(s); } if (type == typeof(LocalTime)) { return(TimePattern.Parse(s).Value); } if (type == typeof(LocalDateTime)) { return(DateTimePattern.Parse(s).Value); } if (type == typeof(bool)) { if (s == "0" || string.Compare(s, "false", StringComparison.OrdinalIgnoreCase) == 0) { return(false); } if (s == "1" || string.Compare(s, "true", StringComparison.OrdinalIgnoreCase) == 0) { return(true); } throw new InvalidDataException($"Parse<bool>('{s}') failure."); } if (type == typeof(char)) { if (s.Length == 1) { return(s[0]); } throw new InvalidDataException($"Parse<char>('{s}') failure."); } if (type.GetTypeInfo().IsEnum) { return(ParseEnum(type, s)); } var utype = Nullable.GetUnderlyingType(type); if (utype != null) { if (utype != typeof(int) && utype != typeof(long) && utype != typeof(double)) { throw new InvalidDataException($"Parse: '{utype.Name}' nullable is not supported."); } if (s.Length == 0) { return(null); } type = utype; } if (s.Length == 0) { return(0); } if (type == typeof(int)) { if (int.TryParse(s, NumberStyles.AllowLeadingSign, NumberFormatInfo.InvariantInfo, out int n)) { return(n); } } else if (type == typeof(long)) { if (long.TryParse(s, NumberStyles.AllowLeadingSign, NumberFormatInfo.InvariantInfo, out long n)) { return(n); } } else if (type == typeof(double)) { if (double.TryParse(s, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out double n)) { return(n); } } throw new InvalidDataException($"Parse<{typeof(T).Name}>('{s}') failure."); }
internal LocalDateTime ReadLocalDateTime(LocalDateTimePattern p) => p.Parse(ReadString()).GetValueOrThrow();
/// <summary> /// Inclusive fromUtc, exclusive toUtc /// </summary> public static TimeSeries LoadSeries(string fullPath, int periodInSeconds, DateTime?fromUtc = null, DateTime?toUtc = null) { if (!File.Exists(fullPath)) { throw new FileNotFoundException($"CsvTimeSeries.LoadSeries {fullPath} not found."); } if (fromUtc != null && fromUtc.Value.Kind != DateTimeKind.Utc) { throw new ArgumentNotUtcException(nameof(fromUtc), fromUtc.Value); } if (toUtc != null && toUtc.Value.Kind != DateTimeKind.Utc) { throw new ArgumentNotUtcException(nameof(toUtc), toUtc.Value); } List <dynamic> lines; var ticks = new List <Tick>(); using (var reader = File.OpenText(fullPath)) { // Reading all lines of the CSV file var csvReader = new CsvReader(reader); lines = csvReader.GetRecords <dynamic>().ToList(); } var period = Period.FromSeconds(periodInSeconds); foreach (var line in lines) { //Console.WriteLine("Expecting input {0}.", Pattern.Format(new LocalDateTime(2014, 5, 26, 13, 45, 22))); ParseResult <LocalDateTime> parseResult = DateTimePattern.Parse(line.date); var date = parseResult.GetValueOrThrow(); // Inclusive from if (fromUtc.HasValue && date.InUtc().ToDateTimeUtc() < fromUtc.Value) { continue; } if (toUtc.HasValue && date.InUtc().ToDateTimeUtc() >= toUtc.Value) { continue; } var open = decimal.Parse(line.open); var high = string.IsNullOrEmpty(line.high) ? (decimal)open : decimal.Parse(line.high); var low = string.IsNullOrEmpty(line.low) ? (decimal)open : decimal.Parse(line.low); decimal close = decimal.Parse(line.close); decimal volume = decimal.Parse(line.volume); ticks.Add(new Tick(period, date, open, high, low, close, volume)); } var fi = new FileInfo(fullPath); return(new TimeSeries(fi.Name, ticks)); }
/// <summary> /// Parses an XML local date/time. /// </summary> /// <param name="value">The value to parse (with 'Z' specifier)</param> /// <returns>The parsed local date/time.</returns> internal static LocalDateTime LocalDateTimeFromXml(string value) { return(XmlLocalDateTimePattern.Parse(value).Value); }
public bool IsValid(string literal) { return(_hasOffset ? _offsetPattern.Parse(literal).Success : _localPattern.Parse(literal).Success); }