-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathString.To.DateTime.cs
44 lines (35 loc) · 1.14 KB
/
String.To.DateTime.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
namespace Ace.CSharp.Extensions;
public static partial class StringExtensions
{
public static DateTime ToDateTime(this string? @this, IFormatProvider? provider)
{
return Convert.ToDateTime(@this, provider);
}
public static DateTime ToDateTimeOrDefault(this string? @this, IFormatProvider? provider, DateTime @default = default)
{
bool isDateTime = TryConvertToDateTime(@this, provider, out var result);
return isDateTime ? result : @default;
}
public static DateTime? ToDateTimeOrNull(this string? @this, IFormatProvider? provider)
{
if (string.IsNullOrWhiteSpace(@this))
{
return null;
}
bool isDateTime = TryConvertToDateTime(@this, provider, out var result);
return isDateTime ? result : null;
}
public static bool TryConvertToDateTime(this string? @this, IFormatProvider? provider, out DateTime result)
{
try
{
result = Convert.ToDateTime(@this, provider);
return true;
}
catch (FormatException)
{
result = default;
return false;
}
}
}