-
Notifications
You must be signed in to change notification settings - Fork 233
/
Copy pathCalDateTime.cs
547 lines (457 loc) · 17.7 KB
/
CalDateTime.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
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
using Ical.Net.Serialization.DataTypes;
using Ical.Net.Utility;
using NodaTime;
using System;
using System.IO;
namespace Ical.Net.DataTypes
{
/// <summary>
/// The iCalendar equivalent of the .NET <see cref="DateTime"/> class.
/// <remarks>
/// In addition to the features of the <see cref="DateTime"/> class, the <see cref="CalDateTime"/>
/// class handles time zone differences, and integrates seamlessly into the iCalendar framework.
/// </remarks>
/// </summary>
public sealed class CalDateTime : EncodableDataType, IDateTime
{
public static CalDateTime Now => new CalDateTime(DateTime.Now);
public static CalDateTime Today => new CalDateTime(DateTime.Today);
private bool _hasDate;
private bool _hasTime;
public CalDateTime() { }
public CalDateTime(IDateTime value)
{
Initialize(value.Value, value.TzId, null);
}
public CalDateTime(DateTime value) : this(value, null) { }
/// <summary>
/// Specifying a `tzId` value will override `value`'s `DateTimeKind` property. If the time zone specified is UTC, the underlying `DateTimeKind` will be
/// `Utc`. If a non-UTC time zone is specified, the underlying `DateTimeKind` property will be `Local`. If no time zone is specified, the `DateTimeKind`
/// property will be left untouched.
/// </summary>
public CalDateTime(DateTime value, string tzId)
{
Initialize(value, tzId, null);
}
public CalDateTime(int year, int month, int day, int hour, int minute, int second)
{
Initialize(year, month, day, hour, minute, second, null, null);
HasTime = true;
}
public CalDateTime(int year, int month, int day, int hour, int minute, int second, string tzId)
{
Initialize(year, month, day, hour, minute, second, tzId, null);
HasTime = true;
}
public CalDateTime(int year, int month, int day, int hour, int minute, int second, string tzId, Calendar cal)
{
Initialize(year, month, day, hour, minute, second, tzId, cal);
HasTime = true;
}
public CalDateTime(int year, int month, int day) : this(year, month, day, 0, 0, 0) { }
public CalDateTime(int year, int month, int day, string tzId) : this(year, month, day, 0, 0, 0, tzId) { }
public CalDateTime(string value)
{
var serializer = new DateTimeSerializer();
CopyFrom(serializer.Deserialize(new StringReader(value)) as ICopyable);
}
private void Initialize(int year, int month, int day, int hour, int minute, int second, string tzId, Calendar cal)
{
Initialize(CoerceDateTime(year, month, day, hour, minute, second, DateTimeKind.Local), tzId, cal);
}
private void Initialize(DateTime value, string tzId, Calendar cal)
{
if (!string.IsNullOrWhiteSpace(tzId) && !tzId.Equals("UTC", StringComparison.OrdinalIgnoreCase))
{
// Definitely local
value = DateTime.SpecifyKind(value, DateTimeKind.Local);
TzId = tzId;
}
else if (string.Equals("UTC", tzId, StringComparison.OrdinalIgnoreCase) || value.Kind == DateTimeKind.Utc)
{
// Probably UTC
value = DateTime.SpecifyKind(value, DateTimeKind.Utc);
TzId = "UTC";
}
Value = new DateTime(value.Year, value.Month, value.Day, value.Hour, value.Minute, value.Second, value.Kind);
HasDate = true;
HasTime = value.Second != 0 || value.Minute != 0 || value.Hour != 0;
AssociatedObject = cal;
}
private DateTime CoerceDateTime(int year, int month, int day, int hour, int minute, int second, DateTimeKind kind)
{
var dt = DateTime.MinValue;
// NOTE: determine if a date/time value exceeds the representable date/time values in .NET.
// If so, let's automatically adjust the date/time to compensate.
// FIXME: should we have a parsing setting that will throw an exception
// instead of automatically adjusting the date/time value to the
// closest representable date/time?
try
{
if (year > 9999)
{
dt = DateTime.MaxValue;
}
else if (year > 0)
{
dt = new DateTime(year, month, day, hour, minute, second, kind);
}
}
catch { }
return dt;
}
public override ICalendarObject AssociatedObject
{
get => base.AssociatedObject;
set
{
if (!Equals(AssociatedObject, value))
{
base.AssociatedObject = value;
}
}
}
public override void CopyFrom(ICopyable obj)
{
base.CopyFrom(obj);
var dt = obj as IDateTime;
if (dt == null)
{
return;
}
_value = dt.Value;
_hasDate = dt.HasDate;
_hasTime = dt.HasTime;
AssociateWith(dt);
}
public bool Equals(CalDateTime other)
=> this == other;
public override bool Equals(object other)
=> other is IDateTime && (CalDateTime)other == this;
public override int GetHashCode()
{
unchecked
{
var hashCode = Value.GetHashCode();
hashCode = (hashCode * 397) ^ HasDate.GetHashCode();
hashCode = (hashCode * 397) ^ AsUtc.GetHashCode();
hashCode = (hashCode * 397) ^ (TzId != null ? TzId.GetHashCode() : 0);
return hashCode;
}
}
public static bool operator <(CalDateTime left, IDateTime right)
=> left != null && right != null && left.AsUtc < right.AsUtc;
public static bool operator >(CalDateTime left, IDateTime right)
=> left != null && right != null && left.AsUtc > right.AsUtc;
public static bool operator <=(CalDateTime left, IDateTime right)
=> left != null && right != null && left.AsUtc <= right.AsUtc;
public static bool operator >=(CalDateTime left, IDateTime right)
=> left != null && right != null && left.AsUtc >= right.AsUtc;
public static bool operator ==(CalDateTime left, IDateTime right)
{
return ReferenceEquals(left, null) || ReferenceEquals(right, null)
? ReferenceEquals(left, right)
: right is CalDateTime
&& left.Value.Equals(right.Value)
&& left.HasDate == right.HasDate
&& left.AsUtc.Equals(right.AsUtc)
&& string.Equals(left.TzId, right.TzId, StringComparison.OrdinalIgnoreCase);
}
public static bool operator !=(CalDateTime left, IDateTime right)
=> !(left == right);
public static TimeSpan operator -(CalDateTime left, IDateTime right)
{
left.AssociateWith(right);
return left.AsUtc - right.AsUtc;
}
public static IDateTime operator -(CalDateTime left, TimeSpan right)
{
var copy = left.Copy<IDateTime>();
copy.Value -= right;
return copy;
}
public static IDateTime operator +(CalDateTime left, TimeSpan right)
{
var copy = left.Copy<IDateTime>();
copy.Value += right;
return copy;
}
public static implicit operator CalDateTime(DateTime left) => new CalDateTime(left);
/// <summary>
/// Converts the date/time to the date/time of the computer running the program. If the DateTimeKind is Unspecified, it's assumed that the underlying
/// Value already represents the system's datetime.
/// </summary>
public DateTime AsSystemLocal
{
get
{
if (Value.Kind == DateTimeKind.Unspecified)
{
return HasTime
? Value
: Value.Date;
}
return HasTime
? Value.ToLocalTime()
: Value.ToLocalTime().Date;
}
}
private DateTime _asUtc = DateTime.MinValue;
/// <summary>
/// Returns a representation of the DateTime in Coordinated Universal Time (UTC)
/// </summary>
public DateTime AsUtc
{
get
{
if (_asUtc == DateTime.MinValue)
{
// In order of weighting:
// 1) Specified TzId
// 2) Value having a DateTimeKind.Utc
// 3) Use the OS's time zone
if (!string.IsNullOrWhiteSpace(TzId))
{
var asLocal = DateUtil.ToZonedDateTimeLeniently(Value, TzId);
_asUtc = asLocal.ToDateTimeUtc();
}
else if (IsUtc || Value.Kind == DateTimeKind.Utc)
{
_asUtc = DateTime.SpecifyKind(Value, DateTimeKind.Utc);
}
else
{
_asUtc = DateTime.SpecifyKind(Value, DateTimeKind.Local).ToUniversalTime();
}
}
return _asUtc;
}
}
private DateTime _value;
public DateTime Value
{
get => _value;
set
{
if (_value == value && _value.Kind == value.Kind)
{
return;
}
_asUtc = DateTime.MinValue;
_value = value;
}
}
public bool IsUtc => _value.Kind == DateTimeKind.Utc;
public bool HasDate
{
get => _hasDate;
set => _hasDate = value;
}
public bool HasTime
{
get => _hasTime;
set => _hasTime = value;
}
private string _tzId = string.Empty;
/// <summary>
/// Setting the TzId to a local time zone will set Value.Kind to Local. Setting TzId to UTC will set Value.Kind to Utc. If the incoming value is null
/// or whitespace, Value.Kind will be set to Unspecified. Setting the TzId will NOT incur a UTC offset conversion under any circumstances. To convert
/// to another time zone, use the ToTimeZone() method.
/// </summary>
public string TzId
{
get
{
if (string.IsNullOrWhiteSpace(_tzId))
{
_tzId = Parameters.Get("TZID");
}
return _tzId;
}
set
{
if (string.Equals(_tzId, value, StringComparison.OrdinalIgnoreCase))
{
return;
}
_asUtc = DateTime.MinValue;
var isEmpty = string.IsNullOrWhiteSpace(value);
if (isEmpty)
{
Parameters.Remove("TZID");
_tzId = null;
Value = DateTime.SpecifyKind(Value, DateTimeKind.Local);
return;
}
var kind = string.Equals(value, "UTC", StringComparison.OrdinalIgnoreCase)
? DateTimeKind.Utc
: DateTimeKind.Local;
Value = DateTime.SpecifyKind(Value, kind);
Parameters.Set("TZID", value);
_tzId = value;
}
}
public string TimeZoneName => TzId;
public int Year => Value.Year;
public int Month => Value.Month;
public int Day => Value.Day;
public int Hour => Value.Hour;
public int Minute => Value.Minute;
public int Second => Value.Second;
public int Millisecond => Value.Millisecond;
public long Ticks => Value.Ticks;
public DayOfWeek DayOfWeek => Value.DayOfWeek;
public int DayOfYear => Value.DayOfYear;
public DateTime Date => Value.Date;
public TimeSpan TimeOfDay => Value.TimeOfDay;
/// <summary>
/// Returns a representation of the IDateTime in the specified time zone
/// </summary>
public IDateTime ToTimeZone(string tzId)
{
if (string.IsNullOrWhiteSpace(tzId))
{
throw new ArgumentException("You must provide a valid time zone id", nameof(tzId));
}
// If TzId is empty, it's a system-local datetime, so we should use the system time zone as the starting point.
var originalTzId = string.IsNullOrWhiteSpace(TzId)
? TimeZoneInfo.Local.Id
: TzId;
var zonedOriginal = DateUtil.ToZonedDateTimeLeniently(Value, originalTzId);
var converted = zonedOriginal.WithZone(DateUtil.GetZone(tzId));
return converted.Zone == DateTimeZone.Utc
? new CalDateTime(converted.ToDateTimeUtc(), tzId)
: new CalDateTime(DateTime.SpecifyKind(converted.ToDateTimeUnspecified(), DateTimeKind.Local), tzId);
}
/// <summary>
/// Returns a DateTimeOffset representation of the Value. If a TzId is specified, it will use that time zone's UTC offset, otherwise it will use the
/// system-local time zone.
/// </summary>
public DateTimeOffset AsDateTimeOffset =>
string.IsNullOrWhiteSpace(TzId)
? new DateTimeOffset(AsSystemLocal)
: DateUtil.ToZonedDateTimeLeniently(Value, TzId).ToDateTimeOffset();
public IDateTime Add(TimeSpan ts) => this + ts;
public IDateTime Subtract(TimeSpan ts) => this - ts;
public TimeSpan Subtract(IDateTime dt) => this - dt;
public IDateTime AddYears(int years)
{
var dt = Copy<IDateTime>();
dt.Value = Value.AddYears(years);
return dt;
}
public IDateTime AddMonths(int months)
{
var dt = Copy<IDateTime>();
dt.Value = Value.AddMonths(months);
return dt;
}
public IDateTime AddDays(int days)
{
var dt = Copy<IDateTime>();
dt.Value = Value.AddDays(days);
return dt;
}
public IDateTime AddHours(int hours)
{
var dt = Copy<IDateTime>();
if (!dt.HasTime && hours % 24 > 0)
{
dt.HasTime = true;
}
dt.Value = Value.AddHours(hours);
return dt;
}
public IDateTime AddMinutes(int minutes)
{
var dt = Copy<IDateTime>();
if (!dt.HasTime && minutes % 1440 > 0)
{
dt.HasTime = true;
}
dt.Value = Value.AddMinutes(minutes);
return dt;
}
public IDateTime AddSeconds(int seconds)
{
var dt = Copy<IDateTime>();
if (!dt.HasTime && seconds % 86400 > 0)
{
dt.HasTime = true;
}
dt.Value = Value.AddSeconds(seconds);
return dt;
}
public IDateTime AddMilliseconds(int milliseconds)
{
var dt = Copy<IDateTime>();
if (!dt.HasTime && milliseconds % 86400000 > 0)
{
dt.HasTime = true;
}
dt.Value = Value.AddMilliseconds(milliseconds);
return dt;
}
public IDateTime AddTicks(long ticks)
{
var dt = Copy<IDateTime>();
dt.HasTime = true;
dt.Value = Value.AddTicks(ticks);
return dt;
}
public bool LessThan(IDateTime dt) => this < dt;
public bool GreaterThan(IDateTime dt) => this > dt;
public bool LessThanOrEqual(IDateTime dt) => this <= dt;
public bool GreaterThanOrEqual(IDateTime dt) => this >= dt;
public void AssociateWith(IDateTime dt)
{
if (AssociatedObject == null && dt.AssociatedObject != null)
{
AssociatedObject = dt.AssociatedObject;
}
else if (AssociatedObject != null && dt.AssociatedObject == null)
{
dt.AssociatedObject = AssociatedObject;
}
}
public int CompareTo(IDateTime dt)
{
if (Equals(dt))
{
return 0;
}
if (this < dt)
{
return -1;
}
if (this > dt)
{
return 1;
}
throw new Exception("An error occurred while comparing two IDateTime values.");
}
public override string ToString() => ToString(null, null);
public string ToString(string format) => ToString(format, null);
public string ToString(string format, IFormatProvider formatProvider)
{
var tz = TimeZoneName;
if (!string.IsNullOrEmpty(tz))
{
tz = " " + tz;
}
if (format != null)
{
return Value.ToString(format, formatProvider) + tz;
}
if (HasTime && HasDate)
{
return Value + tz;
}
if (HasTime)
{
return Value.TimeOfDay + tz;
}
return Value.ToString("d") + tz;
}
}
}