forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDateDatatypes.cs
More file actions
3515 lines (3086 loc) · 118 KB
/
DateDatatypes.cs
File metadata and controls
3515 lines (3086 loc) · 118 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// NpgsqlTypes\DateDatatypes.cs
//
// Author:
// Jon Hanna. (jon@hackcraft.net)
//
// Copyright (C) 2007-2008 The Npgsql Development Team
// npgsql-general@gborg.postgresql.org
// http://gborg.postgresql.org/project/npgsql/projdisplay.php
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph and the following two paragraphs appear in all copies.
//
// IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY
// FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
// ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Npgsql;
//TODO: Lots of convenience methods! There should be nothing you can do with datetime and timestamp that you can't
//do just as well with these - and hence no reason not to choose these if they are appropriate.
//Similarly, lots of documentation is a must.
// Keep the xml comment warning quiet for this file.
#pragma warning disable 1591
namespace NpgsqlTypes
{
/// <summary>
/// Represents the PostgreSQL interval datatype.
/// <remarks>PostgreSQL differs from .NET in how it's interval type doesn't assume 24 hours in a day
/// (to deal with 23- and 25-hour days caused by daylight savings adjustments) and has a concept
/// of months that doesn't exist in .NET's <see cref="TimeSpan"/> class. (Neither datatype
/// has any concessions for leap-seconds).
/// <para>For most uses just casting to and from TimeSpan will work correctly — in particular,
/// the results of subtracting one <see cref="DateTime"/> or the PostgreSQL date, time and
/// timestamp types from another should be the same whether you do so in .NET or PostgreSQL —
/// but if the handling of days and months in PostgreSQL is important to your application then you
/// should use this class instead of <see cref="TimeSpan"/>.</para>
/// <para>If you don't know whether these differences are important to your application, they
/// probably arent! Just use <see cref="TimeSpan"/> and do not use this class directly ☺</para>
/// <para>To avoid forcing unnecessary provider-specific concerns on users who need not be concerned
/// with them a call to <see cref="System.Data.IDataRecord.GetValue(int)"/> on a field containing an
/// <see cref="NpgsqlInterval"/> value will return a <see cref="TimeSpan"/> rather than an
/// <see cref="NpgsqlInterval"/>. If you need the extra functionality of <see cref="NpgsqlInterval"/>
/// then use <see cref="Npgsql.NpgsqlDataReader.GetInterval(Int32)"/>.</para>
/// </remarks>
/// <seealso cref="Ticks"/>
/// <seealso cref="JustifyDays"/>
/// <seealso cref="JustifyMonths"/>
/// <seealso cref="Canonicalize()"/>
/// </summary>
[Serializable]
public struct NpgsqlInterval : IComparable, IComparer, IEquatable<NpgsqlInterval>, IComparable<NpgsqlInterval>,
IComparer<NpgsqlInterval>
{
#region Constants
/// <summary>
/// Represents the number of ticks (100ns periods) in one microsecond. This field is constant.
/// </summary>
public const long TicksPerMicrosecond = TimeSpan.TicksPerMillisecond/1000;
/// <summary>
/// Represents the number of ticks (100ns periods) in one millisecond. This field is constant.
/// </summary>
public const long TicksPerMillsecond = TimeSpan.TicksPerMillisecond;
/// <summary>
/// Represents the number of ticks (100ns periods) in one second. This field is constant.
/// </summary>
public const long TicksPerSecond = TimeSpan.TicksPerSecond;
/// <summary>
/// Represents the number of ticks (100ns periods) in one minute. This field is constant.
/// </summary>
public const long TicksPerMinute = TimeSpan.TicksPerMinute;
/// <summary>
/// Represents the number of ticks (100ns periods) in one hour. This field is constant.
/// </summary>
public const long TicksPerHour = TimeSpan.TicksPerHour;
/// <summary>
/// Represents the number of ticks (100ns periods) in one day. This field is constant.
/// </summary>
public const long TicksPerDay = TimeSpan.TicksPerDay;
/// <summary>
/// Represents the number of hours in one day (assuming no daylight savings adjustments). This field is constant.
/// </summary>
public const int HoursPerDay = 24;
/// <summary>
/// Represents the number of days assumed in one month if month justification or unjustifcation is performed.
/// This is set to 30 for consistency with PostgreSQL. Note that this is means that month adjustments cause
/// a year to be taken as 30 × 12 = 360 rather than 356/366 days.
/// </summary>
public const int DaysPerMonth = 30;
/// <summary>
/// Represents the number of ticks (100ns periods) in one day, assuming 30 days per month. <seealso cref="DaysPerMonth"/>
/// </summary>
public const long TicksPerMonth = TicksPerDay*DaysPerMonth;
/// <summary>
/// Represents the number of months in a year. This field is constant.
/// </summary>
public const int MonthsPerYear = 12;
/// <summary>
/// Represents the maximum <see cref="NpgsqlInterval"/>. This field is read-only.
/// </summary>
public static readonly NpgsqlInterval MaxValue = new NpgsqlInterval(long.MaxValue);
/// <summary>
/// Represents the minimum <see cref="NpgsqlInterval"/>. This field is read-only.
/// </summary>
public static readonly NpgsqlInterval MinValue = new NpgsqlInterval(long.MinValue);
/// <summary>
/// Represents the zero <see cref="NpgsqlInterval"/>. This field is read-only.
/// </summary>
public static readonly NpgsqlInterval Zero = new NpgsqlInterval(0);
#endregion
private readonly int _months;
private readonly int _days;
private readonly long _ticks;
#region Constructors
/// <summary>
/// Initializes a new <see cref="NpgsqlInterval"/> to the specified number of ticks.
/// </summary>
/// <param name="ticks">A time period expressed in 100ns units.</param>
public NpgsqlInterval(long ticks)
{
_months = 0;
_days = 0;
_ticks = ticks;
}
/// <summary>
/// Initializes a new <see cref="NpgsqlInterval"/> to hold the same time as a <see cref="TimeSpan"/>
/// </summary>
/// <param name="timespan">A time period expressed in a <see cref="TimeSpan"/></param>
public NpgsqlInterval(TimeSpan timespan)
: this(timespan.Ticks)
{
}
/// <summary>
/// Initializes a new <see cref="NpgsqlInterval"/> to the specified number of months, days
/// & ticks.
/// </summary>
/// <param name="months">Number of months.</param>
/// <param name="days">Number of days.</param>
/// <param name="ticks">Number of 100ns units.</param>
public NpgsqlInterval(int months, int days, long ticks)
{
_months = months;
_days = days;
_ticks = ticks;
}
/// <summary>
/// Initializes a new <see cref="NpgsqlInterval"/> to the specified number of
/// days, hours, minutes & seconds.
/// </summary>
/// <param name="days">Number of days.</param>
/// <param name="hours">Number of hours.</param>
/// <param name="minutes">Number of minutes.</param>
/// <param name="seconds">Number of seconds.</param>
public NpgsqlInterval(int days, int hours, int minutes, int seconds)
: this(0, days, new TimeSpan(hours, minutes, seconds).Ticks)
{
}
/// <summary>
/// Initializes a new <see cref="NpgsqlInterval"/> to the specified number of
/// days, hours, minutes, seconds & milliseconds.
/// </summary>
/// <param name="days">Number of days.</param>
/// <param name="hours">Number of hours.</param>
/// <param name="minutes">Number of minutes.</param>
/// <param name="seconds">Number of seconds.</param>
/// <param name="milliseconds">Number of milliseconds.</param>
public NpgsqlInterval(int days, int hours, int minutes, int seconds, int milliseconds)
: this(0, days, new TimeSpan(0, hours, minutes, seconds, milliseconds).Ticks)
{
}
/// <summary>
/// Initializes a new <see cref="NpgsqlInterval"/> to the specified number of
/// months, days, hours, minutes, seconds & milliseconds.
/// </summary>
/// <param name="months">Number of months.</param>
/// <param name="days">Number of days.</param>
/// <param name="hours">Number of hours.</param>
/// <param name="minutes">Number of minutes.</param>
/// <param name="seconds">Number of seconds.</param>
/// <param name="milliseconds">Number of milliseconds.</param>
public NpgsqlInterval(int months, int days, int hours, int minutes, int seconds, int milliseconds)
: this(months, days, new TimeSpan(0, hours, minutes, seconds, milliseconds).Ticks)
{
}
/// <summary>
/// Initializes a new <see cref="NpgsqlInterval"/> to the specified number of
/// years, months, days, hours, minutes, seconds & milliseconds.
/// <para>Years are calculated exactly equivalent to 12 months.</para>
/// </summary>
/// <param name="years">Number of years.</param>
/// <param name="months">Number of months.</param>
/// <param name="days">Number of days.</param>
/// <param name="hours">Number of hours.</param>
/// <param name="minutes">Number of minutes.</param>
/// <param name="seconds">Number of seconds.</param>
/// <param name="milliseconds">Number of milliseconds.</param>
public NpgsqlInterval(int years, int months, int days, int hours, int minutes, int seconds, int milliseconds)
: this(years*12 + months, days, new TimeSpan(0, hours, minutes, seconds, milliseconds).Ticks)
{
}
#endregion
#region Whole Parts
/// <summary>
/// The total number of ticks(100ns units) contained. This is the resolution of the
/// <see cref="NpgsqlInterval"/> type. This ignores the number of days and
/// months held. If you want them included use <see cref="UnjustifyInterval()"/> first.
/// <remarks>The resolution of the PostgreSQL
/// interval type is by default 1µs = 1,000 ns. It may be smaller as follows:
/// <list type="number">
/// <item>
/// <term>interval(0)</term>
/// <description>resolution of 1s (1 second)</description>
/// </item>
/// <item>
/// <term>interval(1)</term>
/// <description>resolution of 100ms = 0.1s (100 milliseconds)</description>
/// </item>
/// <item>
/// <term>interval(2)</term>
/// <description>resolution of 10ms = 0.01s (10 milliseconds)</description>
/// </item>
/// <item>
/// <term>interval(3)</term>
/// <description>resolution of 1ms = 0.001s (1 millisecond)</description>
/// </item>
/// <item>
/// <term>interval(4)</term>
/// <description>resolution of 100µs = 0.0001s (100 microseconds)</description>
/// </item>
/// <item>
/// <term>interval(5)</term>
/// <description>resolution of 10µs = 0.00001s (10 microseconds)</description>
/// </item>
/// <item>
/// <term>interval(6) or interval</term>
/// <description>resolution of 1µs = 0.000001s (1 microsecond)</description>
/// </item>
/// </list>
/// <para>As such, if the 100-nanosecond resolution is significant to an application, a PostgreSQL interval will
/// not suffice for those purposes.</para>
/// <para>In more frequent cases though, the resolution of the interval suffices.
/// <see cref="NpgsqlInterval"/> will always suffice to handle the resolution of any interval value, and upon
/// writing to the database, will be rounded to the resolution used.</para>
/// </remarks>
/// <returns>The number of ticks in the instance.</returns>
/// </summary>
public long Ticks
{
get { return _ticks; }
}
/// <summary>
/// Gets the number of whole microseconds held in the instance.
/// <returns>An in the range [-999999, 999999].</returns>
/// </summary>
public int Microseconds
{
get { return (int) ((_ticks/10)%1000000); }
}
/// <summary>
/// Gets the number of whole milliseconds held in the instance.
/// <returns>An in the range [-999, 999].</returns>
/// </summary>
public int Milliseconds
{
get { return (int) ((_ticks/TicksPerMillsecond)%1000); }
}
/// <summary>
/// Gets the number of whole seconds held in the instance.
/// <returns>An in the range [-59, 59].</returns>
/// </summary>
public int Seconds
{
get { return (int) ((_ticks/TicksPerSecond)%60); }
}
/// <summary>
/// Gets the number of whole minutes held in the instance.
/// <returns>An in the range [-59, 59].</returns>
/// </summary>
public int Minutes
{
get { return (int) ((_ticks/TicksPerMinute)%60); }
}
/// <summary>
/// Gets the number of whole hours held in the instance.
/// <remarks>Note that this can be less than -23 or greater than 23 unless <see cref="JustifyDays()"/>
/// has been used to produce this instance.</remarks>
/// </summary>
public int Hours
{
get { return (int) (_ticks/TicksPerHour); }
}
/// <summary>
/// Gets the number of days held in the instance.
/// <remarks>Note that this does not pay attention to a time component with -24 or less hours or
/// 24 or more hours, unless <see cref="JustifyDays()"/> has been called to produce this instance.</remarks>
/// </summary>
public int Days
{
get { return _days; }
}
/// <summary>
/// Gets the number of months held in the instance.
/// <remarks>Note that this does not pay attention to a day component with -30 or less days or
/// 30 or more days, unless <see cref="JustifyMonths()"/> has been called to produce this instance.</remarks>
/// </summary>
public int Months
{
get { return _months; }
}
/// <summary>
/// Returns a <see cref="TimeSpan"/> representing the time component of the instance.
/// <remarks>Note that this may have a value beyond the range ±23:59:59.9999999 unless
/// <see cref="JustifyDays()"/> has been called to produce this instance.</remarks>
/// </summary>
public TimeSpan Time
{
get { return new TimeSpan(_ticks); }
}
#endregion
#region Total Parts
/// <summary>
/// The total number of ticks (100ns units) in the instance, assuming 24 hours in each day and
/// 30 days in a month.
/// </summary>
public long TotalTicks
{
get { return Ticks + Days*TicksPerDay + Months*TicksPerMonth; }
}
/// <summary>
/// The total number of microseconds in the instance, assuming 24 hours in each day and
/// 30 days in a month.
/// </summary>
public double TotalMicroseconds
{
get { return TotalTicks/10d; }
}
/// <summary>
/// The total number of milliseconds in the instance, assuming 24 hours in each day and
/// 30 days in a month.
/// </summary>
public double TotalMilliseconds
{
get { return TotalTicks/(double) TicksPerMillsecond; }
}
/// <summary>
/// The total number of seconds in the instance, assuming 24 hours in each day and
/// 30 days in a month.
/// </summary>
public double TotalSeconds
{
get { return TotalTicks/(double) TicksPerSecond; }
}
/// <summary>
/// The total number of minutes in the instance, assuming 24 hours in each day and
/// 30 days in a month.
/// </summary>
public double TotalMinutes
{
get { return TotalTicks/(double) TicksPerMinute; }
}
/// <summary>
/// The total number of hours in the instance, assuming 24 hours in each day and
/// 30 days in a month.
/// </summary>
public double TotalHours
{
get { return TotalTicks/(double) TicksPerHour; }
}
/// <summary>
/// The total number of days in the instance, assuming 24 hours in each day and
/// 30 days in a month.
/// </summary>
public double TotalDays
{
get { return TotalTicks/(double) TicksPerDay; }
}
/// <summary>
/// The total number of months in the instance, assuming 24 hours in each day and
/// 30 days in a month.
/// </summary>
public double TotalMonths
{
get { return TotalTicks/(double) TicksPerMonth; }
}
#endregion
#region Create From Part
/// <summary>
/// Creates an <see cref="NpgsqlInterval"/> from a number of ticks.
/// </summary>
/// <param name="ticks">The number of ticks (100ns units) in the interval.</param>
/// <returns>A <see cref="Canonicalize()"/>d <see cref="NpgsqlInterval"/> with the given number of ticks.</returns>
public static NpgsqlInterval FromTicks(long ticks)
{
return new NpgsqlInterval(ticks).Canonicalize();
}
/// <summary>
/// Creates an <see cref="NpgsqlInterval"/> from a number of microseconds.
/// </summary>
/// <param name="micro">The number of microseconds in the interval.</param>
/// <returns>A <see cref="Canonicalize()"/>d <see cref="NpgsqlInterval"/> with the given number of microseconds.</returns>
public static NpgsqlInterval FromMicroseconds(double micro)
{
return FromTicks((long) (micro*TicksPerMicrosecond));
}
/// <summary>
/// Creates an <see cref="NpgsqlInterval"/> from a number of milliseconds.
/// </summary>
/// <param name="milli">The number of milliseconds in the interval.</param>
/// <returns>A <see cref="Canonicalize()"/>d <see cref="NpgsqlInterval"/> with the given number of milliseconds.</returns>
public static NpgsqlInterval FromMilliseconds(double milli)
{
return FromTicks((long) (milli*TicksPerMillsecond));
}
/// <summary>
/// Creates an <see cref="NpgsqlInterval"/> from a number of seconds.
/// </summary>
/// <param name="seconds">The number of seconds in the interval.</param>
/// <returns>A <see cref="Canonicalize()"/>d <see cref="NpgsqlInterval"/> with the given number of seconds.</returns>
public static NpgsqlInterval FromSeconds(double seconds)
{
return FromTicks((long) (seconds*TicksPerSecond));
}
/// <summary>
/// Creates an <see cref="NpgsqlInterval"/> from a number of minutes.
/// </summary>
/// <param name="minutes">The number of minutes in the interval.</param>
/// <returns>A <see cref="Canonicalize()"/>d <see cref="NpgsqlInterval"/> with the given number of minutes.</returns>
public static NpgsqlInterval FromMinutes(double minutes)
{
return FromTicks((long) (minutes*TicksPerMinute));
}
/// <summary>
/// Creates an <see cref="NpgsqlInterval"/> from a number of hours.
/// </summary>
/// <param name="hours">The number of hours in the interval.</param>
/// <returns>A <see cref="Canonicalize()"/>d <see cref="NpgsqlInterval"/> with the given number of hours.</returns>
public static NpgsqlInterval FromHours(double hours)
{
return FromTicks((long) (hours*TicksPerHour));
}
/// <summary>
/// Creates an <see cref="NpgsqlInterval"/> from a number of days.
/// </summary>
/// <param name="days">The number of days in the interval.</param>
/// <returns>A <see cref="Canonicalize()"/>d <see cref="NpgsqlInterval"/> with the given number of days.</returns>
public static NpgsqlInterval FromDays(double days)
{
return FromTicks((long) (days*TicksPerDay));
}
/// <summary>
/// Creates an <see cref="NpgsqlInterval"/> from a number of months.
/// </summary>
/// <param name="months">The number of months in the interval.</param>
/// <returns>A <see cref="Canonicalize()"/>d <see cref="NpgsqlInterval"/> with the given number of months.</returns>
public static NpgsqlInterval FromMonths(double months)
{
return FromTicks((long) (months*TicksPerMonth));
}
#endregion
#region Arithmetic
/// <summary>
/// Adds another interval to this instance and returns the result.
/// </summary>
/// <param name="interval">An <see cref="NpgsqlInterval"/> to add to this instance.</param>
/// <returns>An <see cref="NpgsqlInterval"></see> whose values are the sums of the two instances.</returns>
public NpgsqlInterval Add(NpgsqlInterval interval)
{
return new NpgsqlInterval(Months + interval.Months, Days + interval.Days, Ticks + interval.Ticks);
}
/// <summary>
/// Subtracts another interval from this instance and returns the result.
/// </summary>
/// <param name="interval">An <see cref="NpgsqlInterval"/> to subtract from this instance.</param>
/// <returns>An <see cref="NpgsqlInterval"></see> whose values are the differences of the two instances.</returns>
public NpgsqlInterval Subtract(NpgsqlInterval interval)
{
return new NpgsqlInterval(Months - interval.Months, Days - interval.Days, Ticks - interval.Ticks);
}
/// <summary>
/// Returns an <see cref="NpgsqlInterval"/> whose value is the negated value of this instance.
/// </summary>
/// <returns>An <see cref="NpgsqlInterval"/> whose value is the negated value of this instance.</returns>
public NpgsqlInterval Negate()
{
return new NpgsqlInterval(-Months, -Days, -Ticks);
}
/// <summary>
/// This absolute value of this instance. In the case of some, but not all, components being negative,
/// the rules used for justification are used to determine if the instance is positive or negative.
/// </summary>
/// <returns>An <see cref="NpgsqlInterval"/> whose value is the absolute value of this instance.</returns>
public NpgsqlInterval Duration()
{
return UnjustifyInterval().Ticks < 0 ? Negate() : this;
}
#endregion
#region Justification
/// <summary>
/// Equivalent to PostgreSQL's justify_days function.
/// </summary>
/// <returns>An <see cref="NpgsqlInterval"/> based on this one, but with any hours outside of the range [-23, 23]
/// converted into days.</returns>
public NpgsqlInterval JustifyDays()
{
return new NpgsqlInterval(Months, Days + (int) (Ticks/TicksPerDay), Ticks%TicksPerDay);
}
/// <summary>
/// Opposite to PostgreSQL's justify_days function.
/// </summary>
/// <returns>An <see cref="NpgsqlInterval"/> based on this one, but with any days converted to multiples of ±24hours.</returns>
public NpgsqlInterval UnjustifyDays()
{
return new NpgsqlInterval(Months, 0, Ticks + Days*TicksPerDay);
}
/// <summary>
/// Equivalent to PostgreSQL's justify_months function.
/// </summary>
/// <returns>An <see cref="NpgsqlInterval"/> based on this one, but with any days outside of the range [-30, 30]
/// converted into months.</returns>
public NpgsqlInterval JustifyMonths()
{
return new NpgsqlInterval(Months + Days/DaysPerMonth, Days%DaysPerMonth, Ticks);
}
/// <summary>
/// Opposite to PostgreSQL's justify_months function.
/// </summary>
/// <returns>An <see cref="NpgsqlInterval"/> based on this one, but with any months converted to multiples of ±30days.</returns>
public NpgsqlInterval UnjustifyMonths()
{
return new NpgsqlInterval(0, Days + Months*DaysPerMonth, Ticks);
}
/// <summary>
/// Equivalent to PostgreSQL's justify_interval function.
/// </summary>
/// <returns>An <see cref="NpgsqlInterval"/> based on this one,
/// but with any months converted to multiples of ±30days
/// and then with any days converted to multiples of ±24hours</returns>
public NpgsqlInterval JustifyInterval()
{
return JustifyMonths().JustifyDays();
}
/// <summary>
/// Opposite to PostgreSQL's justify_interval function.
/// </summary>
/// <returns>An <see cref="NpgsqlInterval"/> based on this one, but with any months converted to multiples of ±30days and then any days converted to multiples of ±24hours;</returns>
public NpgsqlInterval UnjustifyInterval()
{
return new NpgsqlInterval(Ticks + Days*TicksPerDay + Months*DaysPerMonth*TicksPerDay);
}
/// <summary>
/// Produces a canonical NpgslInterval with 0 months and hours in the range of [-23, 23].
/// <remarks>
/// <para>
/// While the fact that for many purposes, two different <see cref="NpgsqlInterval"/> instances could be considered
/// equivalent (e.g. one with 2days, 3hours and one with 1day 27hours) there are different possible canonical forms.
/// </para><para>
/// E.g. we could move all excess hours into days and all excess days into months and have the most readable form,
/// or we could move everything into the ticks and have the form that allows for the easiest arithmetic) the form
/// chosen has two important properties that make it the best choice.
/// </para><para>First, it is closest two how
/// <see cref="TimeSpan"/> objects are most often represented. Second, it is compatible with results of many
/// PostgreSQL functions, particularly with age() and the results of subtracting one date, time or timestamp from
/// another.
/// </para>
/// <para>Note that the results of casting a <see cref="TimeSpan"/> to <see cref="NpgsqlInterval"/> is
/// canonicalised.</para>
/// </remarks>
/// </summary>
/// <returns>An <see cref="NpgsqlTypes.NpgsqlInterval"/> based on this one, but with months converted to multiples of ±30days and with any hours outside of the range [-23, 23]
/// converted into days.</returns>
public NpgsqlInterval Canonicalize()
{
return new NpgsqlInterval(0, Days + Months*DaysPerMonth + (int) (Ticks/TicksPerDay), Ticks%TicksPerDay);
}
#endregion
#region Casts
/// <summary>
/// Implicit cast of a <see cref="TimeSpan"/> to an <see cref="NpgsqlInterval"/>
/// </summary>
/// <param name="timespan">A <see cref="TimeSpan"/></param>
/// <returns>An eqivalent, canonical, <see cref="NpgsqlInterval"/>.</returns>
public static implicit operator NpgsqlInterval(TimeSpan timespan)
{
return new NpgsqlInterval(timespan).Canonicalize();
}
/// <summary>
/// Implicit cast of an <see cref="NpgsqlInterval"/> to a <see cref="TimeSpan"/>.
/// </summary>
/// <param name="interval">A <see cref="NpgsqlInterval"/>.</param>
/// <returns>An equivalent <see cref="TimeSpan"/>.</returns>
public static explicit operator TimeSpan(NpgsqlInterval interval)
{
return new TimeSpan(interval.Ticks + interval.Days*TicksPerDay + interval.Months*DaysPerMonth*TicksPerDay);
}
#endregion
#region Comparison
/// <summary>
/// Returns true if another <see cref="NpgsqlInterval"/> is exactly the same as this instance.
/// </summary>
/// <param name="other">An <see cref="NpgsqlInterval"/> for comparison.</param>
/// <returns>true if the two <see cref="NpgsqlInterval"/> instances are exactly the same,
/// false otherwise.</returns>
public bool Equals(NpgsqlInterval other)
{
return Ticks == other.Ticks && Days == other.Days && Months == other.Months;
}
/// <summary>
/// Returns true if another object is an <see cref="NpgsqlInterval"/>, that is exactly the same as
/// this instance
/// </summary>
/// <param name="obj">An <see cref="Object"/> for comparison.</param>
/// <returns>true if the argument is an <see cref="NpgsqlInterval"/> and is exactly the same
/// as this one, false otherwise.</returns>
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (obj is NpgsqlInterval)
{
return Equals((NpgsqlInterval) obj);
}
return false;
}
/// <summary>
/// Compares two <see cref="NpgsqlInterval"/> instances.
/// </summary>
/// <param name="x">The first <see cref="NpgsqlInterval"/>.</param>
/// <param name="y">The second <see cref="NpgsqlInterval"/>.</param>
/// <returns>0 if the two are equal or equivalent. A value greater than zero if x is greater than y,
/// a value less than zero if x is less than y.</returns>
public static int Compare(NpgsqlInterval x, NpgsqlInterval y)
{
return x.CompareTo(y);
}
int IComparer<NpgsqlInterval>.Compare(NpgsqlInterval x, NpgsqlInterval y)
{
return x.CompareTo(y);
}
int IComparer.Compare(object x, object y)
{
if (x == null)
{
return y == null ? 0 : 1;
}
if (y == null)
{
return -1;
}
try
{
return ((IComparable) x).CompareTo(y);
}
catch (Exception)
{
throw new ArgumentException();
}
}
/// <summary>
/// A hash code suitable for uses with hashing algorithms.
/// </summary>
/// <returns>An signed integer.</returns>
public override int GetHashCode()
{
return UnjustifyInterval().Ticks.GetHashCode();
}
/// <summary>
/// Compares this instance with another/
/// </summary>
/// <param name="other">An <see cref="NpgsqlInterval"/> to compare this with.</param>
/// <returns>0 if the instances are equal or equivalent. A value less than zero if
/// this instance is less than the argument. A value greater than zero if this instance
/// is greater than the instance.</returns>
public int CompareTo(NpgsqlInterval other)
{
return UnjustifyInterval().Ticks.CompareTo(other.UnjustifyInterval().Ticks);
}
/// <summary>
/// Compares this instance with another/
/// </summary>
/// <param name="other">An object to compare this with.</param>
/// <returns>0 if the argument is an <see cref="NpgsqlInterval"/> and the instances are equal or equivalent.
/// A value less than zero if the argument is an <see cref="NpgsqlInterval"/> and
/// this instance is less than the argument.
/// A value greater than zero if the argument is an <see cref="NpgsqlInterval"/> and this instance
/// is greater than the instance.</returns>
/// A value greater than zero if the argument is null.
/// <exception cref="ArgumentException">The argument is not an <see cref="NpgsqlInterval"/>.</exception>
public int CompareTo(object other)
{
if (other == null)
{
return 1;
}
else if (other is NpgsqlInterval)
{
return CompareTo((NpgsqlInterval) other);
}
else
{
throw new ArgumentException();
}
}
#endregion
#region To And From Strings
/// <summary>
/// Parses a <see cref="String"/> and returns a <see cref="NpgsqlInterval"/> instance.
/// Designed to use the formats generally returned by PostgreSQL.
/// </summary>
/// <param name="str">The <see cref="String"/> to parse.</param>
/// <returns>An <see cref="NpgsqlInterval"/> represented by the argument.</returns>
/// <exception cref="ArgumentNullException">The string was null.</exception>
/// <exception cref="OverflowException">A value obtained from parsing the string exceeded the values allowed for the relevant component.</exception>
/// <exception cref="FormatException">The string was not in a format that could be parsed to produce an <see cref="NpgsqlInterval"/>.</exception>
public static NpgsqlInterval Parse(string str)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
str = str.Replace('s', ' '); //Quick and easy way to catch plurals.
try
{
int years = 0;
int months = 0;
int days = 0;
int hours = 0;
int minutes = 0;
decimal seconds = 0m;
int idx = str.IndexOf("year");
if (idx > 0)
{
years = int.Parse(str.Substring(0, idx));
str = SafeSubstring(str, idx + 5);
}
idx = str.IndexOf("mon");
if (idx > 0)
{
months = int.Parse(str.Substring(0, idx));
str = SafeSubstring(str, idx + 4);
}
idx = str.IndexOf("day");
if (idx > 0)
{
days = int.Parse(str.Substring(0, idx));
str = SafeSubstring(str, idx + 4).Trim();
}
if (str.Length > 0)
{
bool isNegative = str[0] == '-';
string[] parts = str.Split(':');
switch (parts.Length) //One of those times that fall-through would actually be good.
{
case 1:
hours = int.Parse(parts[0]);
break;
case 2:
hours = int.Parse(parts[0]);
minutes = int.Parse(parts[1]);
break;
default:
hours = int.Parse(parts[0]);
minutes = int.Parse(parts[1]);
seconds = decimal.Parse(parts[2], System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
break;
}
if (isNegative)
{
minutes *= -1;
seconds *= -1;
}
}
long ticks = hours*TicksPerHour + minutes*TicksPerMinute + (long) (seconds*TicksPerSecond);
return new NpgsqlInterval(years*MonthsPerYear + months, days, ticks);
}
catch (OverflowException)
{
throw;
}
catch (Exception)
{
throw new FormatException();
}
}
private static string SafeSubstring(string s, int startIndex)
{
if (startIndex >= s.Length)
return string.Empty;
else
return s.Substring(startIndex);
}
/// <summary>
/// Attempt to parse a <see cref="String"/> to produce an <see cref="NpgsqlInterval"/>.
/// </summary>
/// <param name="str">The <see cref="String"/> to parse.</param>
/// <param name="result">(out) The <see cref="NpgsqlInterval"/> produced, or <see cref="Zero"/> if the parsing failed.</param>
/// <returns>true if the parsing succeeded, false otherwise.</returns>
public static bool TryParse(string str, out NpgsqlInterval result)
{
try
{
result = Parse(str);
return true;
}
catch (Exception)
{
result = Zero;
return false;
}
}
/// <summary>
/// Create a <see cref="String"/> representation of the <see cref="NpgsqlInterval"/> instance.
/// The format returned is of the form:
/// [M mon[s]] [d day[s]] [HH:mm:ss[.f[f[f[f[f[f[f[f[f]]]]]]]]]]
/// A zero <see cref="NpgsqlInterval"/> is represented as 00:00:00
/// <remarks>
/// Ticks are 100ns, Postgress resolution is only to 1µs at most. Hence we lose 1 or more decimal
/// precision in storing values in the database. Despite this, this method will output that extra
/// digit of precision. It's forward-compatible with any future increases in resolution up to 100ns,
/// and also makes this ToString() more applicable to any other use-case.
/// </remarks>
/// </summary>
/// <returns>The <see cref="String"/> representation.</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
if (Months != 0)
{
sb.Append(Months).Append(Math.Abs(Months) == 1 ? " mon " : " mons ");
}
if (Days != 0)
{
if (Months < 0 && Days > 0)
{
sb.Append('+');
}
sb.Append(Days).Append(Math.Abs(Days) == 1 ? " day " : " days ");
}
if (Ticks != 0 || sb.Length == 0)
{
if(Ticks < 0)
{
sb.Append('-');
}
else if (Days < 0 || (Days == 0 && Months < 0))
{
sb.Append('+');
}
// calculate total seconds and then subtract total whole minutes in seconds to get just the seconds and fractional part
decimal seconds = _ticks / (decimal)TicksPerSecond - (_ticks / TicksPerMinute) * 60;
sb.Append(Math.Abs(Hours).ToString("D2")).Append(':').Append(Math.Abs(Minutes).ToString("D2")).Append(':').Append(Math.Abs(seconds).ToString("0#.######", System.Globalization.CultureInfo.InvariantCulture.NumberFormat));
}
if (sb[sb.Length - 1] == ' ')
{
sb.Remove(sb.Length - 1, 1);
}
return sb.ToString();
}
#endregion
#region Common Operators
/// <summary>
/// Adds two <see cref="NpgsqlInterval"/> together.
/// </summary>
/// <param name="x">The first <see cref="NpgsqlInterval"/> to add.</param>
/// <param name="y">The second <see cref="NpgsqlInterval"/> to add.</param>
/// <returns>An <see cref="NpgsqlInterval"/> whose values are the sum of the arguments.</returns>
public static NpgsqlInterval operator +(NpgsqlInterval x, NpgsqlInterval y)
{
return x.Add(y);
}
/// <summary>
/// Subtracts one <see cref="NpgsqlInterval"/> from another.
/// </summary>
/// <param name="x">The <see cref="NpgsqlInterval"/> to subtract the other from.</param>
/// <param name="y">The <see cref="NpgsqlInterval"/> to subtract from the other.</param>
/// <returns>An <see cref="NpgsqlInterval"/> whose values are the difference of the arguments</returns>
public static NpgsqlInterval operator -(NpgsqlInterval x, NpgsqlInterval y)
{
return x.Subtract(y);
}
/// <summary>
/// Returns true if two <see cref="NpgsqlInterval"/> are exactly the same.
/// </summary>
/// <param name="x">The first <see cref="NpgsqlInterval"/> to compare.</param>
/// <param name="y">The second <see cref="NpgsqlInterval"/> to compare.</param>
/// <returns>true if the two arguments are exactly the same, false otherwise.</returns>
public static bool operator ==(NpgsqlInterval x, NpgsqlInterval y)
{
return x.Equals(y);