该方法是把字符串转为日期DateOnly,转换失败则返回默日期,具体代码如下:
/// <summary>
/// 字符串转日期,转换失败则返回默认日期
/// </summary>
/// <param name="source">需转换的字符串</param>
/// <param name="dateOnly">默认日期</param>
/// <returns>日期</returns>
public static DateOnly ToDateOnlyOrDefault(this string source, DateOnly dateOnly)
{
if (DateOnly.TryParse(source, CultureInfo.InvariantCulture, DateTimeStyles.None, out var date))
{
return date;
}
return dateOnly;
}