Files
ReminderOrganizer/Core/BirthdayInput.cs

50 lines
2.1 KiB
C#
Raw Permalink Normal View History

#nullable enable
using System;
using System.Globalization;
using System.Text.RegularExpressions;
namespace ReminderOrganizer.Core
{
/// <summary>Parses quick birthday input: "19.3", "19.03.", "19.03.1986", "19.3.86", "1986-03-19".</summary>
public static class BirthdayInput
{
private static readonly Regex DayMonthYear = new(@"^\s*(\d{1,2})\s*[./\-\s]\s*(\d{1,2})\s*\.?\s*(?:[./\-\s]?\s*(\d{2}|\d{4}))?\s*$");
private static readonly Regex Iso = new(@"^\s*(\d{4})-(\d{1,2})-(\d{1,2})\s*$");
public static bool TryParse(string? text, DateTime today, out int day, out int month, out int? year)
{
day = month = 0;
year = null;
if (string.IsNullOrWhiteSpace(text)) return false;
var m = Iso.Match(text);
if (m.Success)
{
year = int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture);
month = int.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture);
day = int.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture);
}
else
{
m = DayMonthYear.Match(text);
if (!m.Success) return false;
day = int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture);
month = int.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture);
if (m.Groups[3].Success)
{
int y = int.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture);
if (m.Groups[3].Value.Length == 2)
y += y > today.Year % 100 ? 1900 : 2000; // "86" → 1986, "05" → 2005
year = y;
}
}
if (month < 1 || month > 12) return false;
if (day < 1 || day > DateTime.DaysInMonth(2000, month)) return false; // 2000: leap year, allows 29.02.
if (year is int yy && (yy < 1900 || yy > today.Year)) return false;
if (year is int y2 && day > DateTime.DaysInMonth(y2, month)) return false;
return true;
}
}
}