3
3
// See the LICENSE file in the project root for more information.
4
4
5
5
using System ;
6
+ using System . Collections . Generic ;
7
+ using System . Diagnostics . CodeAnalysis ;
6
8
using System . Globalization ;
7
9
using System . Text . Json ;
8
10
using System . Text . Json . Serialization ;
@@ -15,7 +17,13 @@ namespace Elastic.Clients.Elasticsearch;
15
17
/// Represents a duration value.
16
18
/// </summary>
17
19
[ JsonConverter ( typeof ( DurationConverter ) ) ]
18
- public sealed class Duration : IComparable < Duration > , IEquatable < Duration > , IUrlParameter
20
+ public sealed class Duration :
21
+ IComparable < Duration > ,
22
+ IEquatable < Duration > ,
23
+ IUrlParameter
24
+ #if NET7_0_OR_GREATER
25
+ , IParsable < Duration >
26
+ #endif
19
27
{
20
28
private const double MicrosecondsInATick = 0.1 ; // 10 ticks = 1 microsecond
21
29
private const double MillisecondsInADay = MillisecondsInAnHour * 24 ;
@@ -390,6 +398,35 @@ private static string ExponentFormat(double d)
390
398
var exponent = ( int ) ( ( bits >> 52 ) & 0x7ffL ) ;
391
399
return new string ( '#' , Math . Max ( 2 , exponent ) ) ;
392
400
}
401
+
402
+ #region IParsable
403
+
404
+ public static Duration Parse ( string s , IFormatProvider ? provider ) =>
405
+ TryParse ( s , provider , out var result ) ? result : throw new FormatException ( ) ;
406
+
407
+ public static bool TryParse ( [ NotNullWhen ( true ) ] string ? s , IFormatProvider ? provider ,
408
+ [ NotNullWhen ( true ) ] out Duration ? result )
409
+ {
410
+ if ( s is null )
411
+ {
412
+ result = null ;
413
+ return false ;
414
+ }
415
+
416
+ try
417
+ {
418
+ result = new Duration ( s ) ;
419
+ }
420
+ catch
421
+ {
422
+ result = null ;
423
+ return false ;
424
+ }
425
+
426
+ return true ;
427
+ }
428
+
429
+ #endregion IParsable
393
430
}
394
431
395
432
internal sealed class DurationConverter : JsonConverter < Duration >
0 commit comments