-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSQLiteConvert.cs
executable file
·2942 lines (2632 loc) · 98.8 KB
/
SQLiteConvert.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
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
/********************************************************
* ADO.NET 2.0 Data Provider for SQLite Version 3.X
* Written by Robert Simpson ([email protected])
*
* Released to the public domain, use at your own risk!
********************************************************/
namespace System.Data.SQLite
{
using System;
#if !NET_COMPACT_20 && TRACE_WARNING
using System.Diagnostics;
#endif
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
/// <summary>
/// This base class provides datatype conversion services for the SQLite provider.
/// </summary>
public abstract class SQLiteConvert
{
/// <summary>
/// The fallback default database type when one cannot be obtained from an
/// existing connection instance.
/// </summary>
private const DbType FallbackDefaultDbType = DbType.Object;
/// <summary>
/// The fallback default database type name when one cannot be obtained from
/// an existing connection instance.
/// </summary>
private static readonly string FallbackDefaultTypeName = String.Empty;
/// <summary>
/// The value for the Unix epoch (e.g. January 1, 1970 at midnight, in UTC).
/// </summary>
protected static readonly DateTime UnixEpoch =
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
#pragma warning disable 414
/// <summary>
/// The value of the OLE Automation epoch represented as a Julian day. This
/// field cannot be removed as the test suite relies upon it.
/// </summary>
private static readonly double OleAutomationEpochAsJulianDay = 2415018.5;
#pragma warning restore 414
/// <summary>
/// The format string for DateTime values when using the InvariantCulture or CurrentCulture formats.
/// </summary>
private const string FullFormat = "yyyy-MM-ddTHH:mm:ss.fffffffK";
/// <summary>
/// This is the minimum Julian Day value supported by this library
/// (148731163200000).
/// </summary>
private static readonly long MinimumJd = computeJD(DateTime.MinValue);
/// <summary>
/// This is the maximum Julian Day value supported by this library
/// (464269060799000).
/// </summary>
private static readonly long MaximumJd = computeJD(DateTime.MaxValue);
/// <summary>
/// An array of ISO-8601 DateTime formats that we support parsing.
/// </summary>
private static string[] _datetimeFormats = new string[] {
"THHmmssK",
"THHmmK",
"HH:mm:ss.FFFFFFFK",
"HH:mm:ssK",
"HH:mmK",
"yyyy-MM-dd HH:mm:ss.FFFFFFFK", /* NOTE: UTC default (5). */
"yyyy-MM-dd HH:mm:ssK",
"yyyy-MM-dd HH:mmK",
"yyyy-MM-ddTHH:mm:ss.FFFFFFFK",
"yyyy-MM-ddTHH:mmK",
"yyyy-MM-ddTHH:mm:ssK",
"yyyyMMddHHmmssK",
"yyyyMMddHHmmK",
"yyyyMMddTHHmmssFFFFFFFK",
"THHmmss",
"THHmm",
"HH:mm:ss.FFFFFFF",
"HH:mm:ss",
"HH:mm",
"yyyy-MM-dd HH:mm:ss.FFFFFFF", /* NOTE: Non-UTC default (19). */
"yyyy-MM-dd HH:mm:ss",
"yyyy-MM-dd HH:mm",
"yyyy-MM-ddTHH:mm:ss.FFFFFFF",
"yyyy-MM-ddTHH:mm",
"yyyy-MM-ddTHH:mm:ss",
"yyyyMMddHHmmss",
"yyyyMMddHHmm",
"yyyyMMddTHHmmssFFFFFFF",
"yyyy-MM-dd",
"yyyyMMdd",
"yy-MM-dd"
};
/// <summary>
/// The internal default format for UTC DateTime values when converting
/// to a string.
/// </summary>
private static readonly string _datetimeFormatUtc = _datetimeFormats[5];
/// <summary>
/// The internal default format for local DateTime values when converting
/// to a string.
/// </summary>
private static readonly string _datetimeFormatLocal = _datetimeFormats[19];
/// <summary>
/// An UTF-8 Encoding instance, so we can convert strings to and from UTF-8
/// </summary>
private static Encoding _utf8 = new UTF8Encoding();
/// <summary>
/// The default DateTime format for this instance.
/// </summary>
internal SQLiteDateFormats _datetimeFormat;
/// <summary>
/// The default DateTimeKind for this instance.
/// </summary>
internal DateTimeKind _datetimeKind;
/// <summary>
/// The default DateTime format string for this instance.
/// </summary>
internal string _datetimeFormatString = null;
/// <summary>
/// Initializes the conversion class
/// </summary>
/// <param name="fmt">The default date/time format to use for this instance</param>
/// <param name="kind">The DateTimeKind to use.</param>
/// <param name="fmtString">The DateTime format string to use.</param>
internal SQLiteConvert(
SQLiteDateFormats fmt,
DateTimeKind kind,
string fmtString
)
{
_datetimeFormat = fmt;
_datetimeKind = kind;
_datetimeFormatString = fmtString;
}
#region UTF-8 Conversion Functions
/// <summary>
/// Converts a string to a UTF-8 encoded byte array sized to include a null-terminating character.
/// </summary>
/// <param name="sourceText">The string to convert to UTF-8</param>
/// <returns>A byte array containing the converted string plus an extra 0 terminating byte at the end of the array.</returns>
public static byte[] ToUTF8(string sourceText)
{
if (sourceText == null) return null;
Byte[] byteArray;
int nlen = _utf8.GetByteCount(sourceText) + 1;
byteArray = new byte[nlen];
nlen = _utf8.GetBytes(sourceText, 0, sourceText.Length, byteArray, 0);
byteArray[nlen] = 0;
return byteArray;
}
/// <summary>
/// Convert a DateTime to a UTF-8 encoded, zero-terminated byte array.
/// </summary>
/// <remarks>
/// This function is a convenience function, which first calls ToString() on the DateTime, and then calls ToUTF8() with the
/// string result.
/// </remarks>
/// <param name="dateTimeValue">The DateTime to convert.</param>
/// <returns>The UTF-8 encoded string, including a 0 terminating byte at the end of the array.</returns>
public byte[] ToUTF8(DateTime dateTimeValue)
{
return ToUTF8(ToString(dateTimeValue));
}
/// <summary>
/// Converts a UTF-8 encoded IntPtr of the specified length into a .NET string
/// </summary>
/// <param name="nativestring">The pointer to the memory where the UTF-8 string is encoded</param>
/// <param name="nativestringlen">The number of bytes to decode</param>
/// <returns>A string containing the translated character(s)</returns>
public virtual string ToString(IntPtr nativestring, int nativestringlen)
{
return UTF8ToString(nativestring, nativestringlen);
}
/// <summary>
/// Converts a UTF-8 encoded IntPtr of the specified length into a .NET string
/// </summary>
/// <param name="nativestring">The pointer to the memory where the UTF-8 string is encoded</param>
/// <param name="nativestringlen">The number of bytes to decode</param>
/// <returns>A string containing the translated character(s)</returns>
public static string UTF8ToString(IntPtr nativestring, int nativestringlen)
{
if (nativestring == IntPtr.Zero || nativestringlen == 0) return String.Empty;
if (nativestringlen < 0)
{
nativestringlen = 0;
while (Marshal.ReadByte(nativestring, nativestringlen) != 0)
nativestringlen++;
if (nativestringlen == 0) return String.Empty;
}
byte[] byteArray = new byte[nativestringlen];
Marshal.Copy(nativestring, byteArray, 0, nativestringlen);
return _utf8.GetString(byteArray, 0, nativestringlen);
}
#endregion
///////////////////////////////////////////////////////////////////////////
#region DateTime Conversion Functions
#region New Julian Day Conversion Methods
/// <summary>
/// Checks if the specified <see cref="Int64" /> is within the
/// supported range for a Julian Day value.
/// </summary>
/// <param name="jd">
/// The Julian Day value to check.
/// </param>
/// <returns>
/// Non-zero if the specified Julian Day value is in the supported
/// range; otherwise, zero.
/// </returns>
private static bool isValidJd(
long jd
)
{
return ((jd >= MinimumJd) && (jd <= MaximumJd));
}
///////////////////////////////////////////////////////////////////////////
/// <summary>
/// Converts a Julian Day value from a <see cref="Double" /> to an
/// <see cref="Int64" />.
/// </summary>
/// <param name="julianDay">
/// The Julian Day <see cref="Double" /> value to convert.
/// </param>
/// <returns>
/// The resulting Julian Day <see cref="Int64" /> value.
/// </returns>
private static long DoubleToJd(
double julianDay
)
{
return (long)Math.Round(julianDay * 86400000.0);
}
///////////////////////////////////////////////////////////////////////////
/// <summary>
/// Converts a Julian Day value from an <see cref="Int64" /> to a
/// <see cref="Double" />.
/// </summary>
/// <param name="jd">
/// The Julian Day <see cref="Int64" /> value to convert.
/// </param>
/// <returns>
/// The resulting Julian Day <see cref="Double" /> value.
/// </returns>
private static double JdToDouble(
long jd
)
{
return (double)(jd / 86400000.0);
}
///////////////////////////////////////////////////////////////////////////
/// <summary>
/// Converts a Julian Day value to a <see cref="DateTime" />.
/// This method was translated from the "computeYMD" function in the
/// "date.c" file belonging to the SQLite core library.
/// </summary>
/// <param name="jd">
/// The Julian Day value to convert.
/// </param>
/// <param name="badValue">
/// The <see cref="DateTime" /> value to return in the event that the
/// Julian Day is out of the supported range. If this value is null,
/// an exception will be thrown instead.
/// </param>
/// <returns>
/// A <see cref="DateTime" /> value that contains the year, month, and
/// day values that are closest to the specified Julian Day value.
/// </returns>
private static DateTime computeYMD(
long jd,
DateTime? badValue
)
{
if (!isValidJd(jd))
{
if (badValue == null)
{
throw new ArgumentException(
"Not a supported Julian Day value.");
}
return (DateTime)badValue;
}
int Z, A, B, C, D, E, X1;
Z = (int)((jd + 43200000) / 86400000);
A = (int)((Z - 1867216.25) / 36524.25);
A = Z + 1 + A - (A / 4);
B = A + 1524;
C = (int)((B - 122.1) / 365.25);
D = (36525 * C) / 100;
E = (int)((B - D) / 30.6001);
X1 = (int)(30.6001 * E);
int day, month, year;
day = B - D - X1;
month = E < 14 ? E - 1 : E - 13;
year = month > 2 ? C - 4716 : C - 4715;
try
{
return new DateTime(year, month, day);
}
catch
{
if (badValue == null)
throw;
return (DateTime)badValue;
}
}
///////////////////////////////////////////////////////////////////////////
/// <summary>
/// Converts a Julian Day value to a <see cref="DateTime" />.
/// This method was translated from the "computeHMS" function in the
/// "date.c" file belonging to the SQLite core library.
/// </summary>
/// <param name="jd">
/// The Julian Day value to convert.
/// </param>
/// <param name="badValue">
/// The <see cref="DateTime" /> value to return in the event that the
/// Julian Day value is out of the supported range. If this value is
/// null, an exception will be thrown instead.
/// </param>
/// <returns>
/// A <see cref="DateTime" /> value that contains the hour, minute, and
/// second, and millisecond values that are closest to the specified
/// Julian Day value.
/// </returns>
private static DateTime computeHMS(
long jd,
DateTime? badValue
)
{
if (!isValidJd(jd))
{
if (badValue == null)
{
throw new ArgumentException(
"Not a supported Julian Day value.");
}
return (DateTime)badValue;
}
int si;
si = (int)((jd + 43200000) % 86400000);
decimal sd;
sd = si / 1000.0M;
si = (int)sd;
int millisecond = (int)((sd - si) * 1000.0M);
sd -= si;
int hour;
hour = si / 3600;
si -= hour * 3600;
int minute;
minute = si / 60;
sd += si - minute * 60;
int second = (int)sd;
try
{
DateTime minValue = DateTime.MinValue;
return new DateTime(
minValue.Year, minValue.Month, minValue.Day,
hour, minute, second, millisecond);
}
catch
{
if (badValue == null)
throw;
return (DateTime)badValue;
}
}
///////////////////////////////////////////////////////////////////////////
/// <summary>
/// Converts a <see cref="DateTime" /> to a Julian Day value.
/// This method was translated from the "computeJD" function in
/// the "date.c" file belonging to the SQLite core library.
/// Since the range of Julian Day values supported by this method
/// includes all possible (valid) values of a <see cref="DateTime" />
/// value, it should be extremely difficult for this method to
/// raise an exception or return an undefined result.
/// </summary>
/// <param name="dateTime">
/// The <see cref="DateTime" /> value to convert. This value
/// will be within the range of <see cref="DateTime.MinValue" />
/// (00:00:00.0000000, January 1, 0001) to
/// <see cref="DateTime.MaxValue" /> (23:59:59.9999999, December
/// 31, 9999).
/// </param>
/// <returns>
/// The nearest Julian Day value corresponding to the specified
/// <see cref="DateTime" /> value.
/// </returns>
private static long computeJD(
DateTime dateTime
)
{
int Y, M, D;
Y = dateTime.Year;
M = dateTime.Month;
D = dateTime.Day;
if (M <= 2)
{
Y--;
M += 12;
}
int A, B, X1, X2;
A = Y / 100;
B = 2 - A + (A / 4);
X1 = 36525 * (Y + 4716) / 100;
X2 = 306001 * (M + 1) / 10000;
long jd;
jd = (long)((X1 + X2 + D + B - 1524.5) * 86400000);
jd += (dateTime.Hour * 3600000) + (dateTime.Minute * 60000) +
(dateTime.Second * 1000) + dateTime.Millisecond;
return jd;
}
#endregion
///////////////////////////////////////////////////////////////////////////
/// <summary>
/// Converts a string into a DateTime, using the DateTimeFormat, DateTimeKind,
/// and DateTimeFormatString specified for the connection when it was opened.
/// </summary>
/// <remarks>
/// Acceptable ISO8601 DateTime formats are:
/// <list type="bullet">
/// <item><description>THHmmssK</description></item>
/// <item><description>THHmmK</description></item>
/// <item><description>HH:mm:ss.FFFFFFFK</description></item>
/// <item><description>HH:mm:ssK</description></item>
/// <item><description>HH:mmK</description></item>
/// <item><description>yyyy-MM-dd HH:mm:ss.FFFFFFFK</description></item>
/// <item><description>yyyy-MM-dd HH:mm:ssK</description></item>
/// <item><description>yyyy-MM-dd HH:mmK</description></item>
/// <item><description>yyyy-MM-ddTHH:mm:ss.FFFFFFFK</description></item>
/// <item><description>yyyy-MM-ddTHH:mmK</description></item>
/// <item><description>yyyy-MM-ddTHH:mm:ssK</description></item>
/// <item><description>yyyyMMddHHmmssK</description></item>
/// <item><description>yyyyMMddHHmmK</description></item>
/// <item><description>yyyyMMddTHHmmssFFFFFFFK</description></item>
/// <item><description>THHmmss</description></item>
/// <item><description>THHmm</description></item>
/// <item><description>HH:mm:ss.FFFFFFF</description></item>
/// <item><description>HH:mm:ss</description></item>
/// <item><description>HH:mm</description></item>
/// <item><description>yyyy-MM-dd HH:mm:ss.FFFFFFF</description></item>
/// <item><description>yyyy-MM-dd HH:mm:ss</description></item>
/// <item><description>yyyy-MM-dd HH:mm</description></item>
/// <item><description>yyyy-MM-ddTHH:mm:ss.FFFFFFF</description></item>
/// <item><description>yyyy-MM-ddTHH:mm</description></item>
/// <item><description>yyyy-MM-ddTHH:mm:ss</description></item>
/// <item><description>yyyyMMddHHmmss</description></item>
/// <item><description>yyyyMMddHHmm</description></item>
/// <item><description>yyyyMMddTHHmmssFFFFFFF</description></item>
/// <item><description>yyyy-MM-dd</description></item>
/// <item><description>yyyyMMdd</description></item>
/// <item><description>yy-MM-dd</description></item>
/// </list>
/// If the string cannot be matched to one of the above formats -OR-
/// the DateTimeFormatString if one was provided, an exception will
/// be thrown.
/// </remarks>
/// <param name="dateText">The string containing either a long integer number of 100-nanosecond units since
/// System.DateTime.MinValue, a Julian day double, an integer number of seconds since the Unix epoch, a
/// culture-independent formatted date and time string, a formatted date and time string in the current
/// culture, or an ISO8601-format string.</param>
/// <returns>A DateTime value</returns>
public DateTime ToDateTime(string dateText)
{
return ToDateTime(dateText, _datetimeFormat, _datetimeKind, _datetimeFormatString);
}
/// <summary>
/// Converts a string into a DateTime, using the specified DateTimeFormat,
/// DateTimeKind and DateTimeFormatString.
/// </summary>
/// <remarks>
/// Acceptable ISO8601 DateTime formats are:
/// <list type="bullet">
/// <item><description>THHmmssK</description></item>
/// <item><description>THHmmK</description></item>
/// <item><description>HH:mm:ss.FFFFFFFK</description></item>
/// <item><description>HH:mm:ssK</description></item>
/// <item><description>HH:mmK</description></item>
/// <item><description>yyyy-MM-dd HH:mm:ss.FFFFFFFK</description></item>
/// <item><description>yyyy-MM-dd HH:mm:ssK</description></item>
/// <item><description>yyyy-MM-dd HH:mmK</description></item>
/// <item><description>yyyy-MM-ddTHH:mm:ss.FFFFFFFK</description></item>
/// <item><description>yyyy-MM-ddTHH:mmK</description></item>
/// <item><description>yyyy-MM-ddTHH:mm:ssK</description></item>
/// <item><description>yyyyMMddHHmmssK</description></item>
/// <item><description>yyyyMMddHHmmK</description></item>
/// <item><description>yyyyMMddTHHmmssFFFFFFFK</description></item>
/// <item><description>THHmmss</description></item>
/// <item><description>THHmm</description></item>
/// <item><description>HH:mm:ss.FFFFFFF</description></item>
/// <item><description>HH:mm:ss</description></item>
/// <item><description>HH:mm</description></item>
/// <item><description>yyyy-MM-dd HH:mm:ss.FFFFFFF</description></item>
/// <item><description>yyyy-MM-dd HH:mm:ss</description></item>
/// <item><description>yyyy-MM-dd HH:mm</description></item>
/// <item><description>yyyy-MM-ddTHH:mm:ss.FFFFFFF</description></item>
/// <item><description>yyyy-MM-ddTHH:mm</description></item>
/// <item><description>yyyy-MM-ddTHH:mm:ss</description></item>
/// <item><description>yyyyMMddHHmmss</description></item>
/// <item><description>yyyyMMddHHmm</description></item>
/// <item><description>yyyyMMddTHHmmssFFFFFFF</description></item>
/// <item><description>yyyy-MM-dd</description></item>
/// <item><description>yyyyMMdd</description></item>
/// <item><description>yy-MM-dd</description></item>
/// </list>
/// If the string cannot be matched to one of the above formats -OR-
/// the DateTimeFormatString if one was provided, an exception will
/// be thrown.
/// </remarks>
/// <param name="dateText">The string containing either a long integer number of 100-nanosecond units since
/// System.DateTime.MinValue, a Julian day double, an integer number of seconds since the Unix epoch, a
/// culture-independent formatted date and time string, a formatted date and time string in the current
/// culture, or an ISO8601-format string.</param>
/// <param name="format">The SQLiteDateFormats to use.</param>
/// <param name="kind">The DateTimeKind to use.</param>
/// <param name="formatString">The DateTime format string to use.</param>
/// <returns>A DateTime value</returns>
public static DateTime ToDateTime(
string dateText,
SQLiteDateFormats format,
DateTimeKind kind,
string formatString
)
{
switch (format)
{
case SQLiteDateFormats.Ticks:
{
return TicksToDateTime(Convert.ToInt64(
dateText, CultureInfo.InvariantCulture), kind);
}
case SQLiteDateFormats.JulianDay:
{
return ToDateTime(Convert.ToDouble(
dateText, CultureInfo.InvariantCulture), kind);
}
case SQLiteDateFormats.UnixEpoch:
{
return UnixEpochToDateTime(Convert.ToInt64(
dateText, CultureInfo.InvariantCulture), kind);
}
case SQLiteDateFormats.InvariantCulture:
{
if (formatString != null)
return DateTime.SpecifyKind(DateTime.ParseExact(
dateText, formatString,
DateTimeFormatInfo.InvariantInfo,
kind == DateTimeKind.Utc ?
DateTimeStyles.AdjustToUniversal :
DateTimeStyles.None),
kind);
else
return DateTime.SpecifyKind(DateTime.Parse(
dateText, DateTimeFormatInfo.InvariantInfo,
kind == DateTimeKind.Utc ?
DateTimeStyles.AdjustToUniversal :
DateTimeStyles.None),
kind);
}
case SQLiteDateFormats.CurrentCulture:
{
if (formatString != null)
return DateTime.SpecifyKind(DateTime.ParseExact(
dateText, formatString,
DateTimeFormatInfo.CurrentInfo,
kind == DateTimeKind.Utc ?
DateTimeStyles.AdjustToUniversal :
DateTimeStyles.None),
kind);
else
return DateTime.SpecifyKind(DateTime.Parse(
dateText, DateTimeFormatInfo.CurrentInfo,
kind == DateTimeKind.Utc ?
DateTimeStyles.AdjustToUniversal :
DateTimeStyles.None),
kind);
}
default: /* ISO-8601 */
{
if (formatString != null)
return DateTime.SpecifyKind(DateTime.ParseExact(
dateText, formatString,
DateTimeFormatInfo.InvariantInfo,
kind == DateTimeKind.Utc ?
DateTimeStyles.AdjustToUniversal :
DateTimeStyles.None),
kind);
else
return DateTime.SpecifyKind(DateTime.ParseExact(
dateText, _datetimeFormats,
DateTimeFormatInfo.InvariantInfo,
kind == DateTimeKind.Utc ?
DateTimeStyles.AdjustToUniversal :
DateTimeStyles.None),
kind);
}
}
}
/// <summary>
/// Converts a julianday value into a DateTime
/// </summary>
/// <param name="julianDay">The value to convert</param>
/// <returns>A .NET DateTime</returns>
public DateTime ToDateTime(double julianDay)
{
return ToDateTime(julianDay, _datetimeKind);
}
/// <summary>
/// Converts a julianday value into a DateTime
/// </summary>
/// <param name="julianDay">The value to convert</param>
/// <param name="kind">The DateTimeKind to use.</param>
/// <returns>A .NET DateTime</returns>
public static DateTime ToDateTime(
double julianDay,
DateTimeKind kind
)
{
long jd = DoubleToJd(julianDay);
DateTime dateTimeYMD = computeYMD(jd, null);
DateTime dateTimeHMS = computeHMS(jd, null);
return new DateTime(
dateTimeYMD.Year, dateTimeYMD.Month, dateTimeYMD.Day,
dateTimeHMS.Hour, dateTimeHMS.Minute, dateTimeHMS.Second,
dateTimeHMS.Millisecond, kind);
}
/// <summary>
/// Converts the specified number of seconds from the Unix epoch into a
/// <see cref="DateTime" /> value.
/// </summary>
/// <param name="seconds">
/// The number of whole seconds since the Unix epoch.
/// </param>
/// <param name="kind">
/// Either Utc or Local time.
/// </param>
/// <returns>
/// The new <see cref="DateTime" /> value.
/// </returns>
internal static DateTime UnixEpochToDateTime(long seconds, DateTimeKind kind)
{
return DateTime.SpecifyKind(UnixEpoch.AddSeconds(seconds), kind);
}
/// <summary>
/// Converts the specified number of ticks since the epoch into a
/// <see cref="DateTime" /> value.
/// </summary>
/// <param name="ticks">
/// The number of whole ticks since the epoch.
/// </param>
/// <param name="kind">
/// Either Utc or Local time.
/// </param>
/// <returns>
/// The new <see cref="DateTime" /> value.
/// </returns>
internal static DateTime TicksToDateTime(long ticks, DateTimeKind kind)
{
return new DateTime(ticks, kind);
}
/// <summary>
/// Converts a DateTime struct to a JulianDay double
/// </summary>
/// <param name="value">The DateTime to convert</param>
/// <returns>The JulianDay value the Datetime represents</returns>
public static double ToJulianDay(DateTime value)
{
return JdToDouble(computeJD(value));
}
/// <summary>
/// Converts a DateTime struct to the whole number of seconds since the
/// Unix epoch.
/// </summary>
/// <param name="value">The DateTime to convert</param>
/// <returns>The whole number of seconds since the Unix epoch</returns>
public static long ToUnixEpoch(DateTime value)
{
return (value.Subtract(UnixEpoch).Ticks / TimeSpan.TicksPerSecond);
}
/// <summary>
/// Returns the DateTime format string to use for the specified DateTimeKind.
/// If <paramref name="formatString" /> is not null, it will be returned verbatim.
/// </summary>
/// <param name="kind">The DateTimeKind to use.</param>
/// <param name="formatString">The DateTime format string to use.</param>
/// <returns>
/// The DateTime format string to use for the specified DateTimeKind.
/// </returns>
private static string GetDateTimeKindFormat(
DateTimeKind kind,
string formatString
)
{
if (formatString != null) return formatString;
return (kind == DateTimeKind.Utc) ? _datetimeFormatUtc : _datetimeFormatLocal;
}
/// <summary>
/// Converts a string into a DateTime, using the DateTimeFormat, DateTimeKind,
/// and DateTimeFormatString specified for the connection when it was opened.
/// </summary>
/// <param name="dateValue">The DateTime value to convert</param>
/// <returns>Either a string containing the long integer number of 100-nanosecond units since System.DateTime.MinValue, a
/// Julian day double, an integer number of seconds since the Unix epoch, a culture-independent formatted date and time
/// string, a formatted date and time string in the current culture, or an ISO8601-format date/time string.</returns>
public string ToString(DateTime dateValue)
{
return ToString(dateValue, _datetimeFormat, _datetimeKind, _datetimeFormatString);
}
/// <summary>
/// Converts a string into a DateTime, using the DateTimeFormat, DateTimeKind,
/// and DateTimeFormatString specified for the connection when it was opened.
/// </summary>
/// <param name="dateValue">The DateTime value to convert</param>
/// <param name="format">The SQLiteDateFormats to use.</param>
/// <param name="kind">The DateTimeKind to use.</param>
/// <param name="formatString">The DateTime format string to use.</param>
/// <returns>Either a string containing the long integer number of 100-nanosecond units since System.DateTime.MinValue, a
/// Julian day double, an integer number of seconds since the Unix epoch, a culture-independent formatted date and time
/// string, a formatted date and time string in the current culture, or an ISO8601-format date/time string.</returns>
public static string ToString(
DateTime dateValue,
SQLiteDateFormats format,
DateTimeKind kind,
string formatString
)
{
switch (format)
{
case SQLiteDateFormats.Ticks:
return dateValue.Ticks.ToString(CultureInfo.InvariantCulture);
case SQLiteDateFormats.JulianDay:
return ToJulianDay(dateValue).ToString(CultureInfo.InvariantCulture);
case SQLiteDateFormats.UnixEpoch:
return ((long)(dateValue.Subtract(UnixEpoch).Ticks / TimeSpan.TicksPerSecond)).ToString();
case SQLiteDateFormats.InvariantCulture:
return dateValue.ToString((formatString != null) ?
formatString : FullFormat, CultureInfo.InvariantCulture);
case SQLiteDateFormats.CurrentCulture:
return dateValue.ToString((formatString != null) ?
formatString : FullFormat, CultureInfo.CurrentCulture);
default:
return (dateValue.Kind == DateTimeKind.Unspecified) ?
DateTime.SpecifyKind(dateValue, kind).ToString(
GetDateTimeKindFormat(kind, formatString),
CultureInfo.InvariantCulture) : dateValue.ToString(
GetDateTimeKindFormat(dateValue.Kind, formatString),
CultureInfo.InvariantCulture);
}
}
/// <summary>
/// Internal function to convert a UTF-8 encoded IntPtr of the specified length to a DateTime.
/// </summary>
/// <remarks>
/// This is a convenience function, which first calls ToString() on the IntPtr to convert it to a string, then calls
/// ToDateTime() on the string to return a DateTime.
/// </remarks>
/// <param name="ptr">A pointer to the UTF-8 encoded string</param>
/// <param name="len">The length in bytes of the string</param>
/// <returns>The parsed DateTime value</returns>
internal DateTime ToDateTime(IntPtr ptr, int len)
{
return ToDateTime(ToString(ptr, len));
}
#endregion
/// <summary>
/// Smart method of splitting a string. Skips quoted elements, removes the quotes.
/// </summary>
/// <remarks>
/// This split function works somewhat like the String.Split() function in that it breaks apart a string into
/// pieces and returns the pieces as an array. The primary differences are:
/// <list type="bullet">
/// <item><description>Only one character can be provided as a separator character</description></item>
/// <item><description>Quoted text inside the string is skipped over when searching for the separator, and the quotes are removed.</description></item>
/// </list>
/// Thus, if splitting the following string looking for a comma:<br/>
/// One,Two, "Three, Four", Five<br/>
/// <br/>
/// The resulting array would contain<br/>
/// [0] One<br/>
/// [1] Two<br/>
/// [2] Three, Four<br/>
/// [3] Five<br/>
/// <br/>
/// Note that the leading and trailing spaces were removed from each item during the split.
/// </remarks>
/// <param name="source">Source string to split apart</param>
/// <param name="separator">Separator character</param>
/// <returns>A string array of the split up elements</returns>
public static string[] Split(string source, char separator)
{
char[] toks = new char[2] { '\"', separator };
char[] quot = new char[1] { '\"' };
int n = 0;
List<string> ls = new List<string>();
string s;
while (source.Length > 0)
{
n = source.IndexOfAny(toks, n);
if (n == -1) break;
if (source[n] == toks[0])
{
//source = source.Remove(n, 1);
n = source.IndexOfAny(quot, n + 1);
if (n == -1)
{
//source = "\"" + source;
break;
}
n++;
//source = source.Remove(n, 1);
}
else
{
s = source.Substring(0, n).Trim();
if (s.Length > 1 && s[0] == quot[0] && s[s.Length - 1] == s[0])
s = s.Substring(1, s.Length - 2);
source = source.Substring(n + 1).Trim();
if (s.Length > 0) ls.Add(s);
n = 0;
}
}
if (source.Length > 0)
{
s = source.Trim();
if (s.Length > 1 && s[0] == quot[0] && s[s.Length - 1] == s[0])
s = s.Substring(1, s.Length - 2);
ls.Add(s);
}
string[] ar = new string[ls.Count];
ls.CopyTo(ar, 0);
return ar;
}
/// <summary>
/// Splits the specified string into multiple strings based on a separator
/// and returns the result as an array of strings.
/// </summary>
/// <param name="value">
/// The string to split into pieces based on the separator character. If
/// this string is null, null will always be returned. If this string is
/// empty, an array of zero strings will always be returned.
/// </param>
/// <param name="separator">
/// The character used to divide the original string into sub-strings.
/// This character cannot be a backslash or a double-quote; otherwise, no
/// work will be performed and null will be returned.
/// </param>
/// <param name="keepQuote">
/// If this parameter is non-zero, all double-quote characters will be
/// retained in the returned list of strings; otherwise, they will be
/// dropped.
/// </param>
/// <param name="error">
/// Upon failure, this parameter will be modified to contain an appropriate
/// error message.
/// </param>
/// <returns>
/// The new array of strings or null if the input string is null -OR- the
/// separator character is a backslash or a double-quote -OR- the string
/// contains an unbalanced backslash or double-quote character.
/// </returns>
internal static string[] NewSplit(
string value,
char separator,
bool keepQuote,
ref string error
)
{
const char EscapeChar = '\\';
const char QuoteChar = '\"';
//
// NOTE: It is illegal for the separator character to be either a
// backslash or a double-quote because both of those characters
// are used for escaping other characters (e.g. the separator
// character).
//
if ((separator == EscapeChar) || (separator == QuoteChar))
{
error = "separator character cannot be the escape or quote characters";
return null;
}
if (value == null)
{
error = "string value to split cannot be null";
return null;
}
int length = value.Length;
if (length == 0)
return new string[0];
List<string> list = new List<string>();
StringBuilder element = new StringBuilder();
int index = 0;
bool escape = false;
bool quote = false;
while (index < length)
{
char character = value[index++];
if (escape)
{
//
// HACK: Only consider the escape character to be an actual
// "escape" if it is followed by a reserved character;
// otherwise, emit the original escape character and
// the current character in an effort to help preserve
// the original string content.
//
if ((character != EscapeChar) &&
(character != QuoteChar) &&