-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathDateTimeUtil.cs
1004 lines (849 loc) · 32.4 KB
/
DateTimeUtil.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
using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using System.Threading;
using System.Diagnostics;
using DigitalPlatform.Core;
namespace DigitalPlatform.IO
{
#if REMOVED
/// <summary>
/// DateTime功能扩展函数
/// </summary>
public class DateTimeUtil
{
// 分析期限参数
public static int ParsePeriodUnit(string strPeriod,
string strDefaultUnit,
out long lValue,
out string strUnit,
out string strError)
{
lValue = 0;
strUnit = "";
strError = "";
strPeriod = strPeriod.Trim();
if (String.IsNullOrEmpty(strPeriod) == true)
{
strError = "期限字符串为空";
return -1;
}
string strValue = "";
for (int i = 0; i < strPeriod.Length; i++)
{
if (strPeriod[i] >= '0' && strPeriod[i] <= '9')
{
strValue += strPeriod[i];
}
else
{
strUnit = strPeriod.Substring(i).Trim();
break;
}
}
// 将strValue转换为数字
try
{
lValue = Convert.ToInt64(strValue);
}
catch (Exception)
{
strError = "期限参数数字部分'" + strValue + "'格式不合法";
return -1;
}
if (String.IsNullOrEmpty(strUnit) == true)
strUnit = strDefaultUnit;
if (String.IsNullOrEmpty(strUnit) == true)
strUnit = "day"; // 缺省单位为"天"
strUnit = strUnit.ToLower(); // 统一转换为小写
return 0;
}
// 按照时间单位,把时间值零头去除,正规化,便于后面计算差额
/// <summary>
/// 按照时间基本单位,去掉零头,便于互相计算(整单位的)差额。
/// 算法是先转换为本地时间,去掉零头,再转换回 GMT 时间
/// </summary>
/// <param name="strUnit">时间单位。day/hour之一。如果为空,相当于 day</param>
/// <param name="time">要处理的时间。为 GMT 时间</param>
/// <param name="strError">返回出错信息</param>
/// <returns>-1: 出错; 0: 成功</returns>
public static int RoundTime(string strUnit,
ref DateTime time,
out string strError)
{
strError = "";
time = time.ToLocalTime();
if (strUnit == "day" || string.IsNullOrEmpty(strUnit) == true)
{
time = new DateTime(time.Year, time.Month, time.Day,
12, 0, 0, 0);
}
else if (strUnit == "hour")
{
time = new DateTime(time.Year, time.Month, time.Day,
time.Hour, 0, 0, 0);
}
else
{
strError = "未知的时间单位 '" + strUnit + "'";
return -1;
}
time = time.ToUniversalTime();
return 0;
}
public static string ToDateString(DateTime day)
{
return day.Year.ToString() + "/" + day.Month.ToString() + "/" + day.Day.ToString();
}
public static string ToMonthString(DateTime day)
{
return day.Year.ToString() + "/" + day.Month.ToString();
}
public static string ToYearString(DateTime day)
{
return day.Year.ToString();
}
// 将日期字符串解析为起止范围日期
// throw:
// Exception
public static void ParseDateRange(string strText,
out string strStartDate,
out string strEndDate)
{
strStartDate = "";
strEndDate = "";
int nRet = strText.IndexOf("-");
if (nRet == -1)
{
// 没有'-'
if (strText.Length == 4)
{
strStartDate = strText + "0101";
strEndDate = strText + "1231";
return;
}
if (strText.Length == 6)
{
strStartDate = strText + "01";
DateTime start = DateTimeUtil.Long8ToDateTime(strStartDate);
DateTime end = start.AddMonths(1);
end = new DateTime(end.Year, end.Month, 1); // 下月1号
end = end.AddDays(-1); // 上月最后一号
strEndDate = strText + end.Day;
return;
}
if (strText.Length == 8)
{
// 单日
strStartDate = strText;
strEndDate = "";
return;
}
// text-level: 用户提示
throw new Exception(
string.Format("日期字符串 '{0}' 格式不正确。应当为4/6/8字符",
strText)
);
}
else
{
string strLeft = "";
string strRight = "";
strLeft = strText.Substring(0, nRet).Trim();
strRight = strText.Substring(nRet + 1).Trim();
if (strLeft.Length != strRight.Length)
{
// text-level: 用户提示
throw new Exception(
string.Format("日期字符串 '{0}' 格式不正确。横杠左边的部分 '{1}' 和右边的部分 '{2}' 字符数应相等。",
strText,
strLeft,
strRight)
);
}
if (strLeft.Length == 4)
{
strStartDate = strLeft + "0101";
strEndDate = strRight + "1231";
return;
}
if (strLeft.Length == 6)
{
strStartDate = strLeft + "01";
DateTime start = DateTimeUtil.Long8ToDateTime(strRight + "01");
DateTime end = start.AddMonths(1);
end = new DateTime(end.Year, end.Month, 1); // 下月1号
end = end.AddDays(-1); // 上月最后一号
strEndDate = strRight + end.Day;
return;
}
if (strLeft.Length == 8)
{
// 单日
strStartDate = strLeft;
strEndDate = strRight;
return;
}
// text-level: 用户提示
throw new Exception(
string.Format("日期字符串 '{0}' 格式不正确。横杠左边或者右边的部分,应当为4/6/8字符",
strText)
);
}
}
public static DateTime ParseFreeTimeString(string strTime)
{
DateTime parsedBack;
string[] formats = {
"yyyy",
"yyyy.M",
"yyyy.MM",
"yyyy.MMM",
"yyyy.M.d",
"yyyy.MM.dd",
"yyyy.MMM.ddd",
"yyyy/M",
"yyyy/MM",
"yyyy/MMM",
"yyyy/M/d",
"yyyy/MM/dd",
"yyyy/MMM/ddd",
};
bool bRet = DateTime.TryParseExact(strTime,
formats,
DateTimeFormatInfo.InvariantInfo,
DateTimeStyles.None,
out parsedBack);
if (bRet == false)
{
bRet = DateTime.TryParse(strTime,
out parsedBack);
if (bRet == false)
{
string strError = "时间字符串 '" + strTime + "' 无法解析";
throw new Exception(strError);
}
}
return parsedBack;
}
public static string ForcePublishTime8(string strPublishTime)
{
strPublishTime = CanonicalizePublishTimeString(strPublishTime);
if (strPublishTime.Length > 8)
strPublishTime = strPublishTime.Substring(0, 8);
return strPublishTime;
}
// 规范化8字符的日期字符串
public static string CanonicalizePublishTimeString(string strText)
{
if (strText.Length == 4)
{
strText = strText + "0101";
goto END1;
}
if (strText.Length == 6)
{
strText = strText + "01";
goto END1;
}
if (strText.Length == 8)
goto END1;
if (strText.Length == 10)
goto END1;
throw new Exception("出版日期字符串 '" + strText + "' 格式不正确");
END1:
// 检查一下时间字符串是否属于存在的时间
string strTest = strText.Substring(0, 8);
try
{
DateTimeUtil.Long8ToDateTime(strTest);
}
catch (System.ArgumentOutOfRangeException /*ex*/)
{
throw new Exception("日期字符串 '" + strText + "' 不正确: 出现了不可能的年、月、日值");
}
catch (Exception ex)
{
throw new Exception("日期字符串 '" + strText + "' 不正确: " + ex.Message);
}
return strText;
}
// 比较HTTP header字段里面的时间。不比较millisecond部分
public static long CompareHeaderTime(DateTime time1, DateTime time2)
{
time1 = new DateTime(time1.Year, time1.Month, time1.Day, time1.Hour, time1.Minute, time1.Second);
time2 = new DateTime(time2.Year, time2.Month, time2.Day, time2.Hour, time2.Minute, time2.Second);
return time1.Ticks - time2.Ticks;
}
public static int Date8toRfc1123(string strOrigin,
out string strTarget,
out string strError)
{
strError = "";
strTarget = "";
strOrigin = strOrigin.Replace("-", "");
// 格式为 20060625, 需要转换为rfc
if (strOrigin.Length != 8)
{
strError = "源日期字符串 '" + strOrigin + "' 格式不正确,应为8字符";
return -1;
}
IFormatProvider culture = new CultureInfo("zh-CN", true);
DateTime time;
try
{
time = DateTime.ParseExact(strOrigin, "yyyyMMdd", culture);
}
catch
{
strError = "日期字符串 '" + strOrigin + "' 字符串转换为DateTime对象时出错";
return -1;
}
time = time.ToUniversalTime();
strTarget = DateTimeUtil.Rfc1123DateTimeString(time);
return 0;
}
// 返回下一月日历上的同一天
public static DateTime NextMonth(DateTime start)
{
int nDayDelta = 0;
int nYear = start.Year;
int nMonth = start.Month;
int nDay = start.Day;
if (nMonth == 12)
{
nYear++;
nMonth = 1;
}
else
{
nMonth++;
}
while (true)
{
try
{
start = new DateTime(nYear, nMonth, nDay - nDayDelta);
}
catch
{
nDayDelta++;
continue;
}
return start;
}
}
// 返回下一个年份
// parameters:
// strYear 4字符的年份
public static string NextYear(string strYear)
{
Debug.Assert(strYear.Length == 4, "");
long v = Convert.ToInt64(strYear);
return (v+1).ToString().PadLeft(4, '0');
}
// 返回下一年日历上的同一天
public static DateTime NextYear(DateTime start)
{
int nDelta = 0;
while (true)
{
try
{
start = new DateTime(start.Year + 1, start.Month, start.Day - nDelta);
}
catch
{
nDelta++;
continue;
}
return start;
}
}
// 为8字符密排日期格式加上'-'
public static string AddHyphenToString8(string strDate,
string strHyphen)
{
if (String.IsNullOrEmpty(strDate) == true)
return strDate;
if (strDate.Length == 4)
return strDate;
if (strDate.Length == 6)
return strDate.Substring(0, 4)
+ strHyphen + strDate.Substring(4, 2);
if (strDate.Length == 8)
return strDate.Substring(0, 4)
+ strHyphen + strDate.Substring(4, 2)
+ strHyphen + strDate.Substring(6, 2);
return strDate;
}
public static string DateTimeToString8(DateTime time)
{
return time.Year.ToString().PadLeft(4, '0')
+ time.Month.ToString().PadLeft(2, '0')
+ time.Day.ToString().PadLeft(2, '0');
}
public static long DateTimeToLong8(DateTime time)
{
return Convert.ToInt64(time.Year.ToString().PadLeft(4, '0')
+ time.Month.ToString().PadLeft(2, '0')
+ time.Day.ToString().PadLeft(2, '0'));
}
public static DateTime Long8ToDateTime(long lDay)
{
int nYear = Convert.ToInt32(lDay.ToString().PadLeft(8, '0').Substring(0, 4));
int nMonth = Convert.ToInt32(lDay.ToString().PadLeft(8, '0').Substring(4, 2));
int nDay = Convert.ToInt32(lDay.ToString().PadLeft(8, '0').Substring(6, 2));
return new DateTime(nYear, nMonth, nDay);
}
// 可能会抛出异常
public static DateTime Long8ToDateTime(string strDate8)
{
if (strDate8.Length != 8)
throw new Exception("日期字符串格式必须为8字符。");
int nYear = Convert.ToInt32(strDate8.Substring(0, 4));
int nMonth = Convert.ToInt32(strDate8.Substring(4, 2));
int nDay = Convert.ToInt32(strDate8.Substring(6, 2));
try
{
return new DateTime(nYear, nMonth, nDay);
}
catch (System.ArgumentOutOfRangeException ex)
{
throw new ArgumentException("字符串 '"+strDate8+"' 是一个不可能出现的日期", ex);
}
}
#if NO
// 将RFC1123时间字符串转换为本地一般时间字符串
// exception: 不会抛出异常
public static string LocalTime(string strRfc1123Time)
{
try
{
if (String.IsNullOrEmpty(strRfc1123Time) == true)
return "";
return DateTimeUtil.Rfc1123DateTimeStringToLocal(strRfc1123Time, "G");
}
catch (Exception /*ex*/) // 2008/10/28
{
return "时间字符串 '" + strRfc1123Time + "' 格式错误,不是合法的RFC1123格式";
}
}
#endif
// 将RFC1123时间字符串转换为本地一般时间字符串
// exception: 不会抛出异常
public static string LocalTime(string strRfc1123Time,
string strFormat = "G")
{
try
{
if (String.IsNullOrEmpty(strRfc1123Time) == true)
return "";
return DateTimeUtil.Rfc1123DateTimeStringToLocal(strRfc1123Time, strFormat);
}
catch (Exception /*ex*/) // 2008/10/28
{
return "时间字符串 '" + strRfc1123Time + "' 格式错误,不是合法的RFC1123格式";
}
}
// 将RFC1123时间字符串转换为本地一般日期字符串
// exception: 不会抛出异常
public static string LocalDate(string strRfc1123Time)
{
try
{
if (String.IsNullOrEmpty(strRfc1123Time) == true)
return "";
return DateTimeUtil.Rfc1123DateTimeStringToLocal(strRfc1123Time, "d"); // "yyyy-MM-dd"
}
catch (Exception /*ex*/) // 2008/10/28
{
return "日期字符串 '" + strRfc1123Time + "' 格式错误,不是合法的RFC1123格式";
}
}
// 返回满足RFC1123的时间值字符串
// 注意time应该在调用前转换为gmt时间值
public static string Rfc1123DateTimeString(DateTime time)
{
// System.Globalization.DateTimeFormatInfo info = new System.Globalization.DateTimeFormatInfo();
#if NO
CultureInfo en = new CultureInfo("en-US");
CultureInfo save = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = en;
#endif
string strTime = time.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", // info.RFC1123Pattern,
DateTimeFormatInfo.InvariantInfo);
#if NO
Thread.CurrentThread.CurrentCulture = save;
#endif
return strTime;
}
// parameters:
// time local时间,不是GMT时间
public static string Rfc1123DateTimeStringEx(DateTime time)
{
// System.Globalization.DateTimeFormatInfo info = new System.Globalization.DateTimeFormatInfo();
#if NO
CultureInfo en = new CultureInfo("en-US");
CultureInfo save = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = en;
#endif
string strTime = time.ToString("ddd, dd MMM yyyy HH':'mm':'ss ",
DateTimeFormatInfo.InvariantInfo);
string strTimeZone = time.ToString("zzz").Replace(":", "");
if (strTimeZone == "+0000"
|| strTimeZone == "-0000")
strTimeZone = "GMT";
#if NO
Thread.CurrentThread.CurrentCulture = save;
#endif
return strTime + strTimeZone;
}
public static DateTime FromUTimeString(string strTime)
{
// 自定义格式字符串为“yyyy'-'MM'-'dd HH':'mm':'ss'Z'”。
// 无法描述时区。隐含表达。
IFormatProvider culture = new CultureInfo("zh-CN", true);
return DateTime.ParseExact(strTime,
"u",
culture);
}
static TimeSpan GetOffset(string strDigital)
{
if (strDigital.Length != 5)
throw new Exception("strDigital必须为5字符");
int hours = Convert.ToInt32(strDigital.Substring(1, 2));
int minutes = Convert.ToInt32(strDigital.Substring(3, 2));
TimeSpan offset = new TimeSpan(hours, minutes, 0);
if (strDigital[0] == '-')
offset = new TimeSpan(offset.Ticks * -1);
return offset;
}
// 将RFC1123字符串中的timezone部分分离出来
// parameters:
// strMain [out]去掉timezone以后的左边部分// ,并去掉左边逗号以左的部分
// strTimeZone [out]timezone部分
static int SplitRfc1123TimeZoneString(string strTimeParam,
out string strMain,
out string strTimeZone,
out TimeSpan offset,
out string strError)
{
strError = "";
strMain = "";
strTimeZone = "";
offset = new TimeSpan(0);
int nRet = 0;
string strTime = strTimeParam.Trim();
/*
// 去掉逗号以左的部分
int nRet = strTime.IndexOf(",");
if (nRet != -1)
strTime = strTime.Substring(nRet + 1).Trim();
* */
// 一位字母
if (strTime.Length > 2
&& strTime[strTime.Length - 2] == ' ')
{
strMain = strTime.Substring(0, strTime.Length - 2).Trim();
strTimeZone = strTime.Substring(strTime.Length - 1);
if (strTimeZone == "J")
{
strError = "RFC1123字符串 '" + strTimeParam + "' 格式错误: 最后一位TimeZone字符,不能为'J'";
return -1;
}
if (strTimeZone == "Z")
return 0;
int nHours = 0;
if (strTimeZone[0] >= 'A' && strTimeZone[0] < 'J')
nHours = -(strTimeZone[0] - 'A' + 1);
else if (strTimeZone[0] >= 'K' && strTimeZone[0] <= 'M')
nHours = -(strTimeZone[0] - 'B' + 1);
else if (strTimeZone[0] >= 'N' && strTimeZone[0] <= 'Y')
nHours = strTimeZone[0] - 'N' + 1;
offset = new TimeSpan(nHours, 0, 0);
return 0;
}
// ( "+" / "-") 4DIGIT
if (strTime.Length > 5
&& (strTime[strTime.Length - 5] == '+' || strTime[strTime.Length - 5] == '-'))
{
strMain = strTime.Substring(0, strTime.Length - 5).Trim();
strTimeZone = strTime.Substring(strTime.Length - 5);
try
{
offset = GetOffset(strTimeZone);
}
catch (Exception ex)
{
strError = ExceptionUtil.GetAutoText(ex);
return -1;
}
return 0;
}
string[] modes = {
"GMT",
"UT",
"EST",
"EDT",
"CST",
"CDT",
"MST",
"MDT",
"PST",
"PDT"};
if (strTime.Length <= 3)
{
strError = "RFC1123字符串 '" + strTimeParam + "' 格式错误: 字符数不足";
return -1;
}
string strPart = strTime.Substring(strTime.Length - 3);
foreach (string mode in modes)
{
nRet = strPart.LastIndexOf(mode);
if (nRet != -1)
{
nRet = strTime.LastIndexOf(mode);
Debug.Assert(nRet != -1, "");
strMain = strTime.Substring(0, nRet).Trim();
strTimeZone = mode;
if (strTimeZone == "GMT" || strTimeZone == "UT")
return 0;
string strDigital = "";
switch (strTimeZone)
{
case "EST":
strDigital = "-0500";
break;
case "EDT":
strDigital = "-0400";
break;
case "CST":
strDigital = "-0600";
break;
case "CDT":
strDigital = "-0500";
break;
case "MST":
strDigital = "-0700";
break;
case "MDT":
strDigital = "-0600";
break;
case "PST":
strDigital = "-0800";
break;
case "PDT":
strDigital = "-0700";
break;
default:
strError = "error";
return -1;
}
try
{
offset = GetOffset(strDigital);
}
catch (Exception ex)
{
strError = ExceptionUtil.GetAutoText(ex);
return -1;
}
return 0;
}
}
strError = "RFC1123字符串 '" + strTimeParam + "' 格式错误: TimeZone部分不合法";
return -1;
}
public static bool TryParseRfc1123DateTimeString(string strTime, out DateTime time)
{
try
{
time = FromRfc1123DateTimeString(strTime);
return true;
}
catch
{
time = new DateTime(0);
return false;
}
}
// 把字符串转换为DateTime对象
// 注意返回的是GMT时间
// 注意可能抛出异常
public static DateTime FromRfc1123DateTimeString(string strTime)
{
if (string.IsNullOrEmpty(strTime) == true)
throw new Exception("时间字符串为空");
string strError = "";
string strMain = "";
string strTimeZone = "";
TimeSpan offset;
// 将RFC1123字符串中的timezone部分分离出来
// parameters:
// strMain [out]去掉timezone以后的左边部分
// strTimeZone [out]timezone部分
int nRet = SplitRfc1123TimeZoneString(strTime,
out strMain,
out strTimeZone,
out offset,
out strError);
if (nRet == -1)
throw new Exception(strError);
DateTime parsedBack;
string[] formats = {
"ddd, dd MMM yyyy HH':'mm':'ss", // [ddd, ] 'GMT'
"dd MMM yyyy HH':'mm':'ss",
"ddd, dd MMM yyyy HH':'mm",
"dd MMM yyyy HH':'mm",
};
bool bRet = DateTime.TryParseExact(strMain,
formats,
DateTimeFormatInfo.InvariantInfo,
DateTimeStyles.None,
out parsedBack);
if (bRet == false)
{
strError = "时间字符串 '" + strTime + "' 不是RFC1123格式";
throw new Exception(strError);
}
return parsedBack - offset;
}
#if NO
// 把字符串转换为DateTime对象
// 注意返回的是GMT时间
// 注意可能抛出异常
public static DateTime FromRfc1123DateTimeString(string strTime)
{
if (string.IsNullOrEmpty(strTime) == true)
throw new Exception("时间字符串为空");
string strError = "";
string strMain = "";
string strTimeZone = "";
TimeSpan offset;
// 将RFC1123字符串中的timezone部分分离出来
// parameters:
// strMain [out]去掉timezone以后的左边部分
// strTimeZone [out]timezone部分
int nRet = SplitRfc1123TimeZoneString(strTime,
out strMain,
out strTimeZone,
out offset,
out strError);
if (nRet == -1)
throw new Exception(strError);
System.Globalization.DateTimeFormatInfo info = new System.Globalization.DateTimeFormatInfo();
CultureInfo en = new CultureInfo("en-US");
CultureInfo save = Thread.CurrentThread.CurrentCulture;
DateTime parsedBack = DateTime.ParseExact(strMain + " GMT",
info.RFC1123Pattern,
en.DateTimeFormat/*,
DateTimeStyles.AdjustToUniversal*/
);
Thread.CurrentThread.CurrentCulture = save;
return parsedBack - offset;
}
#endif
// 将RFC1123时间字符串转换为本地表现形态字符串
// 注意可能抛出异常
public static string Rfc1123DateTimeStringToLocal(string strTime)
{
if (String.IsNullOrEmpty(strTime) == true)
return "";
return FromRfc1123DateTimeString(strTime).ToLocalTime().ToString();
#if NO
System.Globalization.DateTimeFormatInfo info = new System.Globalization.DateTimeFormatInfo();
CultureInfo en = new CultureInfo("en-US");
CultureInfo save = Thread.CurrentThread.CurrentCulture;
DateTime parsedBack = DateTime.ParseExact(strTime,
info.RFC1123Pattern,
en.DateTimeFormat/*,
DateTimeStyles.AdjustToUniversal*/
);
Thread.CurrentThread.CurrentCulture = save;
DateTime localTime = TimeZone.CurrentTimeZone.ToLocalTime(parsedBack);
return localTime.ToString();
#endif
}
// 将RFC1123时间字符串转换为本地表现形态字符串
// 注意可能抛出异常
public static string Rfc1123DateTimeStringToLocal(string strTime,
string strFormat)
{
if (String.IsNullOrEmpty(strTime) == true)
return "";
#if NO
System.Globalization.DateTimeFormatInfo info = new System.Globalization.DateTimeFormatInfo();
CultureInfo en = new CultureInfo("en-US");
CultureInfo save = Thread.CurrentThread.CurrentCulture;
DateTime parsedBack = DateTime.ParseExact(strTime,
info.RFC1123Pattern,
en.DateTimeFormat
);
Thread.CurrentThread.CurrentCulture = save;
#endif
DateTime localTime = TimeZone.CurrentTimeZone.ToLocalTime(
FromRfc1123DateTimeString(strTime)
);
return localTime.ToString(strFormat);
}
// 将u时间字符串转换为本地表现形态字符串
public static string uDateTimeStringToLocal(string strTime)
{
if (String.IsNullOrEmpty(strTime) == true)
return "";
#if NO
System.Globalization.DateTimeFormatInfo info = new System.Globalization.DateTimeFormatInfo();
CultureInfo en = new CultureInfo("en-US");
CultureInfo save = Thread.CurrentThread.CurrentCulture;
#endif
DateTime parsedBack = DateTime.ParseExact(strTime,
"yyyy-MM-dd HH:mm:ssZ",
DateTimeFormatInfo.InvariantInfo
// en.DateTimeFormat
);
#if NO
Thread.CurrentThread.CurrentCulture = save;
#endif
DateTime localTime = TimeZone.CurrentTimeZone.ToLocalTime(parsedBack);
return localTime.ToString("yyyy-MM-dd HH:mm:ss");
}
//
public static string DateTimeString(DateTime time)
{
System.Globalization.DateTimeFormatInfo info = new System.Globalization.DateTimeFormatInfo();
#if NO
CultureInfo en = new CultureInfo("en-US");
CultureInfo save = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = en;
#endif
string strTime = time.ToString(info.LongTimePattern,
DateTimeFormatInfo.InvariantInfo);
#if NO
Thread.CurrentThread.CurrentCulture = save;
#endif
return strTime;
}
public static DateTime ToDateTime(string strTime)
{
System.Globalization.DateTimeFormatInfo info = new System.Globalization.DateTimeFormatInfo();
#if NO
CultureInfo en = new CultureInfo("en-US");
CultureInfo save = Thread.CurrentThread.CurrentCulture;
#endif
DateTime parsedBack = DateTime.ParseExact(strTime,
info.LongTimePattern,
DateTimeFormatInfo.InvariantInfo
// en.DateTimeFormat
);
#if NO
Thread.CurrentThread.CurrentCulture = save;
#endif
// DateTime localTime = TimeZone.CurrentTimeZone.ToLocalTime(parsedBack);
//return localTime.ToString();
return parsedBack;
}
}