This repository has been archived by the owner on Oct 23, 2019. It is now read-only.
/
DateTime.cs
2300 lines (1917 loc) · 79.2 KB
/
DateTime.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
/*
Copyright (c) 2004-2006 Tomas Matousek and Pavel Novak.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
TODO:
- sunset/sunrise calculations changed (PHP 5.1.2)
- Added support for exif date format in strtotime(). (PHP 5.1.3)
*/
using System;
using System.IO;
using System.Text;
using System.Globalization;
using PHP.Core;
using PHP.Core.Reflection;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
#if SILVERLIGHT
using PHP.CoreCLR;
#endif
namespace PHP.Library
{
#region DateTime
/// <summary>
/// Representation of date and time.
/// </summary>
#if !SILVERLIGHT
[Serializable]
#endif
[ImplementsType("DateTime")]
public class __PHP__DateTime : PhpObject
{
#region Constants
public const string ATOM = PhpDateTime.FormatAtom;// @"Y-m-d\TH:i:sP";
public const string COOKIE = PhpDateTime.FormatCookie;// @"l, d-M-y H:i:s T";
public const string ISO8601 = PhpDateTime.FormatISO8601;// @"Y-m-d\TH:i:sO";
public const string RFC822 = PhpDateTime.FormatRFC822;// @"D, d M y H:i:s O";
public const string RFC850 = PhpDateTime.FormatRFC850;// @"l, d-M-y H:i:s T";
public const string RFC1036 = PhpDateTime.FormatRFC1036;// @"D, d M y H:i:s O";
public const string RFC1123 = PhpDateTime.FormatRFC1123;// @"D, d M Y H:i:s O";
public const string RFC2822 = PhpDateTime.FormatRFC2822;// @"D, d M Y H:i:s O";
public const string RFC3339 = PhpDateTime.FormatRFC3339;// @"Y-m-d\TH:i:sP";
public const string RSS = PhpDateTime.FormatRSS;// @"D, d M Y H:i:s O";
public const string W3C = PhpDateTime.FormatW3C;// @"Y-m-d\TH:i:sP";
#endregion
#region Fields
// dont see what these are for, no fields/props on php DateTime obj?
//public PhpReference date = new PhpSmartReference();
//public PhpReference timezone_type = new PhpSmartReference();
//public PhpReference timezone = new PhpSmartReference();
/// <summary>
/// Get the date-time value, stored in UTC
/// </summary>
internal DateTime Time { get; private set; }
/// <summary>
/// Get the time zone for this DateTime object
/// </summary>
internal TimeZoneInfo TimeZone { get; private set; }
#endregion
#region Construction
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public __PHP__DateTime(ScriptContext context, bool newInstance)
: base(context, newInstance)
{ }
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public __PHP__DateTime(ScriptContext context, DTypeDesc caller)
: base(context, caller)
{ }
#if !SILVERLIGHT
/// <summary>Deserializing constructor.</summary>
protected __PHP__DateTime(SerializationInfo info, StreamingContext context)
: base(info, context)
{ }
#endif
#endregion
#region Methods
private static DateTime StrToTime(string timestr)
{
if (string.IsNullOrEmpty(timestr) || timestr.EqualsOrdinalIgnoreCase("now"))
{
return DateTime.UtcNow;
}
else
{
var result = PhpDateTime.StringToTime(timestr);
if (result is int)
{
return DateTimeUtils.UnixTimeStampToUtc((int)result);
}
else
{
return DateTime.UtcNow;
}
}
}
// public __construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
[ImplementsMethod]
public object __construct(ScriptContext/*!*/context, [Optional]object time, [Optional]object timezone)
{
if (timezone == Arg.Default || timezone == null)
{
TimeZone = PhpTimeZone.CurrentTimeZone;
}
else
{
var datetimezone = timezone as DateTimeZone;
if (datetimezone == null)
{
PhpException.InvalidArgumentType("timezone", "DateTimeZone");
TimeZone = PhpTimeZone.CurrentTimeZone;
}
else
{
TimeZone = datetimezone.timezone;
}
}
if (TimeZone == null)
{
PhpException.InvalidArgument("timezone");
return null;
}
var timestr = (time == Arg.Default) ? "now" : PHP.Core.Convert.ObjectToString(time);
this.Time = StrToTime(timestr);
//this.date.Value = this.Time.ToString("yyyy-mm-dd HH:mm:ss");
//this.timezone_type.Value = 3;
//this.timezone.Value = TimeZone.Id;
return null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object __construct(object instance, PhpStack stack)
{
var arg1 = stack.PeekValueOptional(1);
var arg2 = stack.PeekValueOptional(2);
stack.RemoveFrame();
return ((__PHP__DateTime)instance).__construct(stack.Context, arg1, arg2);
}
[ImplementsMethod]
public object setTimeZone(ScriptContext/*!*/context, object timezone)
{
if (timezone == null)
{
PhpException.ArgumentNull("timezone");
return false;
}
var tz = timezone as DateTimeZone;
if (tz == null)
{
PhpException.InvalidArgumentType("timezone", "DateTimeZone");
return false;
}
this.TimeZone = tz.timezone;
return this;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object setTimeZone(object instance, PhpStack stack)
{
var tz = stack.PeekValue(1);
stack.RemoveFrame();
return ((__PHP__DateTime)instance).setTimeZone(stack.Context, tz);
}
[ImplementsMethod]
public object format(ScriptContext/*!*/context, object format)
{
if (format == null)
{
PhpException.ArgumentNull("format");
return false;
}
string fm = format.ToString();
if (string.IsNullOrEmpty(fm))
{
return false;
}
return PhpDateTime.FormatDate(fm, this.Time, this.TimeZone);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object format(object instance, PhpStack stack)
{
var format = stack.PeekValue(1);
stack.RemoveFrame();
return ((__PHP__DateTime)instance).format(stack.Context, format);
}
[ImplementsMethod]
public object getOffset(ScriptContext/*!*/context)
{
if (this.TimeZone == null)
return false;
return (int)this.TimeZone.BaseUtcOffset.TotalSeconds;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object getOffset(object instance, PhpStack stack)
{
stack.RemoveFrame();
return ((__PHP__DateTime)instance).getOffset(stack.Context);
}
[ImplementsMethod]
public object modify(ScriptContext/*!*/context, object modify)
{
if (modify == null)
{
PhpException.ArgumentNull("modify");
return false;
}
string strtime = PHP.Core.Convert.ObjectToString(modify);
this.Time = StrToTime(strtime);
return this;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object modify(object instance, PhpStack stack)
{
var modify = stack.PeekValue(1);
stack.RemoveFrame();
return ((__PHP__DateTime)instance).modify(stack.Context, modify);
}
[ImplementsMethod]
public static object createFromFormat(ScriptContext/*!*/context, object format, object time, [Optional]object timezone)
{
// arguments
var tz = (timezone is DateTimeZone) ? ((DateTimeZone)timezone).timezone : PhpTimeZone.CurrentTimeZone;
string formatstr = PhpVariable.AsString(format);
string timestr = PhpVariable.AsString(time);
if (formatstr == null)
{
PhpException.InvalidArgument("format");
return false;
}
if (timestr == null)
{
PhpException.InvalidArgument("time");
return false;
}
// create DateTime from format+time
int i = 0; // position in <timestr>
foreach (var c in formatstr)
{
switch (c)
{
//case 'd':
//case 'j':
// var day = PHP.Library.StrToTime.DateInfo.ParseUnsignedInt(timestr, ref i, 2);
// // ... use day
// break;
//case 'F':
//case 'M':
// // parse ...
// break;
default:
if (i < timestr.Length && timestr[i] == c)
{
// match
i++;
}
else
{
// not match
PhpException.InvalidArgument("time"); // time not matching format
return false;
}
break;
}
}
if (i < timestr.Length)
{
PhpException.InvalidArgument("time"); // time not matching format
return false;
}
////
//return new __PHP__DateTime(context, true)
//{
// //Time = new DateTime(year, month, day, hour, minute, second, millisecond),
// TimeZone = tz,
//};
throw new NotImplementedException();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object createFromFormat(object instance, PhpStack stack)
{
var format = stack.PeekValue(1);
var time = stack.PeekValue(2);
var timezone = stack.PeekValueOptional(3);
stack.RemoveFrame();
return createFromFormat(stack.Context, format, time, timezone);
}
#endregion
}
#endregion
/// <summary>
/// Functions for date and time manipulation.
/// </summary>
/// <threadsafety static="true"/>
[ImplementsExtension(LibraryDescriptor.ExtDate)]
public static class PhpDateTime
{
/// <summary>
/// Gets the current local time with respect to the current PHP time zone.
/// </summary>
public static DateTime Now
{
get
{
return TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, PhpTimeZone.CurrentTimeZone);
}
}
#region Constants
[ImplementsConstant("DATE_ATOM")]
public const string FormatAtom = @"Y-m-d\TH:i:sO";
[ImplementsConstant("DATE_COOKIE")]
public const string FormatCookie = @"D, d M Y H:i:s T";
[ImplementsConstant("DATE_ISO8601")]
public const string FormatISO8601 = @"Y-m-d\TH:i:sO";
[ImplementsConstant("DATE_RFC822")]
public const string FormatRFC822 = @"D, d M y H:i:s O";
[ImplementsConstant("DATE_RFC850")]
public const string FormatRFC850 = @"l, d-M-y H:i:s T";
[ImplementsConstant("DATE_RFC1123")]
public const string FormatRFC1123 = @"D, d M Y H:i:s T";
[ImplementsConstant("DATE_RFC1036")]
public const string FormatRFC1036 = @"l, d-M-y H:i:s T";
[ImplementsConstant("DATE_RFC2822")]
public const string FormatRFC2822 = @"D, d M Y H:i:s T";
[ImplementsConstant("DATE_RFC3339")]
public const string FormatRFC3339 = @"Y-m-d\TH:i:sP";
[ImplementsConstant("DATE_RSS")]
public const string FormatRSS = @"D, d M Y H:i:s T";
[ImplementsConstant("DATE_W3C")]
public const string FormatW3C = @"Y-m-d\TH:i:sO";
#endregion
#region date_format, date_create, date_offset_get, date_modify
[ImplementsFunction("date_format")]
[return: CastToFalse]
public static object DateFormat(__PHP__DateTime datetime, string format)
{
// TODO: format it properly
return FormatDate(format, datetime.Time, datetime.TimeZone);
}
/// <summary>
/// Alias of new <see cref="DateTime"/>
/// </summary>
[ImplementsFunction("date_create")]
[return: CastToFalse]
public static object DateCreate(ScriptContext/*!*/context)
{
return DateCreate(context, null, null);
}
/// <summary>
/// Alias of new <see cref="DateTime"/>
/// </summary>
[ImplementsFunction("date_create")]
[return: CastToFalse]
public static object DateCreate(ScriptContext/*!*/context, string time)
{
return DateCreate(context, time, null);
}
/// <summary>
/// Alias of new <see cref="DateTime"/>
/// </summary>
[ImplementsFunction("date_create")]
[return: CastToFalse]
public static object DateCreate(ScriptContext/*!*/context, string time, DateTimeZone timezone)
{
var dt = new __PHP__DateTime(context, true);
dt.__construct(context, time, timezone);
return dt;
}
/// <summary>
/// Returns new DateTime object formatted according to the specified format.
/// </summary>
/// <param name="format">The format that the passed in string should be in.</param>
/// <param name="time">String representing the time.</param>
/// <returns></returns>
[ImplementsFunction("date_create_from_format")]
[return: CastToFalse]
public static __PHP__DateTime DateCreateFromFormat(ScriptContext/*!*/context, string format, string time)
{
return __PHP__DateTime.createFromFormat(context, format, time, Arg.Default) as __PHP__DateTime;
}
/// <summary>
/// Returns new DateTime object formatted according to the specified format.
/// </summary>
/// <param name="format">The format that the passed in string should be in.</param>
/// <param name="time">String representing the time.</param>
/// <param name="timezone">A DateTimeZone object representing the desired time zone.</param>
/// <returns></returns>
[ImplementsFunction("date_create_from_format")]
[return:CastToFalse]
public static __PHP__DateTime DateCreateFromFormat(ScriptContext/*!*/context, string format, string time, DateTimeZone timezone)
{
return __PHP__DateTime.createFromFormat(context, format, time, timezone) as __PHP__DateTime;
}
/// <summary>
/// Alias of DateTime::getOffset().
/// </summary>
[ImplementsFunction("date_offset_get")]
[return: CastToFalse]
public static int DateOffsetGet(__PHP__DateTime datetime)
{
if (datetime == null)
{
PhpException.ArgumentNull("datetime");
return -1;
}
if (datetime.TimeZone == null)
return -1;
return (int)datetime.TimeZone.BaseUtcOffset.TotalSeconds;
}
/// <summary>
/// Alias of DateTime::modify().
/// </summary>
[ImplementsFunction("date_modify")]
[return: CastToFalse]
public static __PHP__DateTime DateModify(ScriptContext/*!*/context, __PHP__DateTime datetime, string modify)
{
return datetime.modify(context, modify) as __PHP__DateTime;
}
#endregion
#region date, idate, gmdate
/// <summary>
/// Returns a string formatted according to the given format string using the current local time.
/// </summary>
/// <param name="format">Format definition for output.</param>
/// <returns>Formatted string.</returns>
[ImplementsFunction("date")]
public static string FormatDate(string format)
{
return FormatDate(format, DateTime.UtcNow, PhpTimeZone.CurrentTimeZone);
}
/// <summary>
/// Returns a string formatted according to the given format string using the given integer timestamp.
/// </summary>
/// <param name="format">Format definition for output.</param>
/// <param name="timestamp">Nuber of seconds since 1970 specifying a date.</param>
/// <returns>Formatted string.</returns>
[ImplementsFunction("date")]
public static string FormatDate(string format, int timestamp)
{
return FormatDate(format, DateTimeUtils.UnixTimeStampToUtc(timestamp), PhpTimeZone.CurrentTimeZone);
}
/// <summary>
/// Identical to the date() function except that the time returned is Greenwich Mean Time (GMT)
/// </summary>
/// <param name="format">Format definition for output.</param>
/// <returns>Formatted string.</returns>
[ImplementsFunction("gmdate")]
public static string FormatUtcDate(string format)
{
return FormatDate(format, DateTime.UtcNow, DateTimeUtils.UtcTimeZone);
}
/// <summary>
/// Identical to the date() function except that the time returned is Greenwich Mean Time (GMT)
/// </summary>
/// <param name="format">Format definition for output.</param>
/// <param name="timestamp">Nuber of seconds since 1970 specifying a date.</param>
/// <returns>Formatted string.</returns>
[ImplementsFunction("gmdate")]
public static string FormatUtcDate(string format, int timestamp)
{
return FormatDate(format, DateTimeUtils.UnixTimeStampToUtc(timestamp), DateTimeUtils.UtcTimeZone);
}
/// <summary>
/// Returns a part of current time.
/// </summary>
/// <param name="format">Format definition for output.</param>
/// <returns>Part of the date, e.g. month or hours.</returns>
[ImplementsFunction("idate")]
public static int GetDatePart(string format)
{
if (format == null || format.Length != 1)
PhpException.InvalidArgument("format");
return GetDatePart(format[0], DateTime.UtcNow, PhpTimeZone.CurrentTimeZone);
}
/// <summary>
/// Returns a part of a specified timestamp.
/// </summary>
/// <param name="format">Format definition for output.</param>
/// <param name="timestamp">Nuber of seconds since 1970 specifying a date.</param>
/// <returns>Part of the date, e.g. month or hours.</returns>
[ImplementsFunction("idate")]
public static int GetDatePart(string format, int timestamp)
{
if (format == null || format.Length != 1)
PhpException.InvalidArgument("format");
return GetDatePart(format[0], DateTimeUtils.UnixTimeStampToUtc(timestamp), PhpTimeZone.CurrentTimeZone);
}
private static int GetDatePart(char format, DateTime utc, TimeZoneInfo/*!*/ zone)
{
DateTime local = TimeZoneInfo.ConvertTimeFromUtc(utc, zone);// zone.ToLocalTime(utc);
switch (format)
{
case 'B':
// Swatch Beat (Internet Time) - 000 through 999
return GetSwatchBeat(utc);
case 'd':
// Day of the month
return local.Day;
case 'g':
case 'h':
// 12-hour format:
return (local.Hour == 12) ? 12 : local.Hour % 12;
case 'G':
case 'H':
// 24-hour format:
return local.Hour;
case 'i':
return local.Minute;
case 'I':
return zone.IsDaylightSavingTime(local) ? 1 : 0;
case 'j':
goto case 'd';
case 'L':
return DateTime.IsLeapYear(local.Year) ? 1 : 0;
case 'm':
return local.Month;
case 'n':
goto case 'm';
case 's':
return local.Second;
case 't':
return DateTime.DaysInMonth(local.Year, local.Month);
case 'U':
return DateTimeUtils.UtcToUnixTimeStamp(utc);
case 'w':
// day of the week - 0 (for Sunday) through 6 (for Saturday)
return (int)local.DayOfWeek;
case 'W':
{
// ISO-8601 week number of year, weeks starting on Monday:
int week, year;
GetIsoWeekAndYear(local, out week, out year);
return week;
}
case 'y':
return local.Year % 100;
case 'Y':
return local.Year;
case 'z':
return local.DayOfYear - 1;
case 'Z':
return (int)zone.GetUtcOffset(local).TotalSeconds;
default:
PhpException.InvalidArgument("format");
return 0;
}
}
internal static string FormatDate(string format, DateTime utc, TimeZoneInfo zone)
{
Debug.Assert(zone != null);
if (format == null)
return string.Empty;
DateTime local = TimeZoneInfo.ConvertTimeFromUtc(utc, zone);
// here we are creating output string
StringBuilder result = new StringBuilder();
bool escape = false;
foreach (char ch in format)
{
if (escape)
{
result.Append(ch);
escape = false;
continue;
}
switch (ch)
{
case 'a':
// Lowercase Ante meridiem and Post meridiem - am or pm
result.Append(local.ToString("tt", DateTimeFormatInfo.InvariantInfo).ToLowerInvariant());
break;
case 'A':
// Uppercase Ante meridiem and Post meridiem - AM or PM
result.Append(local.ToString("tt", DateTimeFormatInfo.InvariantInfo));
break;
case 'B':
// Swatch Beat (Internet Time) - 000 through 999
result.AppendFormat("{0:000}", GetSwatchBeat(utc));
break;
case 'c':
{
// ISO 8601 date (added in PHP 5) 2004-02-12T15:19:21+00:00
result.Append(local.ToString("yyyy-MM-dd'T'HH:mm:ss", DateTimeFormatInfo.InvariantInfo));
TimeSpan offset = zone.GetUtcOffset(local);
result.AppendFormat("{0}{1:00}:{2:00}", (offset.Ticks < 0) ? ""/*offset.Hours already < 0*/ : "+", offset.Hours, offset.Minutes);
break;
}
case 'd':
// Day of the month, 2 digits with leading zeros - 01 to 31
result.Append(local.ToString("dd", DateTimeFormatInfo.InvariantInfo));
break;
case 'e':
// Timezone identifier (added in PHP 5.1.0)
result.Append(zone.Id);
break;
case 'D':
// A textual representation of a day, three letters - Mon through Sun
result.Append(local.ToString("ddd", DateTimeFormatInfo.InvariantInfo));
break;
case 'F':
// A full textual representation of a month, such as January or March - January through December
result.Append(local.ToString("MMMM", DateTimeFormatInfo.InvariantInfo));
break;
case 'g':
// 12-hour format of an hour without leading zeros - 1 through 12
result.Append(local.ToString("%h", DateTimeFormatInfo.InvariantInfo));
break;
case 'G':
// 24-hour format of an hour without leading zeros - 0 through 23
result.Append(local.ToString("%H", DateTimeFormatInfo.InvariantInfo));
break;
case 'h':
// 12-hour format of an hour with leading zeros - 01 through 12
result.Append(local.ToString("hh", DateTimeFormatInfo.InvariantInfo));
break;
case 'H':
// 24-hour format of an hour with leading zeros - 00 through 23
result.Append(local.ToString("HH", DateTimeFormatInfo.InvariantInfo));
break;
case 'i':
// Minutes with leading zeros - 00 to 59
result.Append(local.ToString("mm", DateTimeFormatInfo.InvariantInfo));
break;
case 'I':
// Whether or not the date is in daylights savings time - 1 if Daylight Savings Time, 0 otherwise.
result.Append(zone.IsDaylightSavingTime(local) ? "1" : "0");
break;
case 'j':
// Day of the month without leading zeros - 1 to 31
result.Append(local.ToString("%d", DateTimeFormatInfo.InvariantInfo));
break;
case 'l':
// A full textual representation of the day of the week - Sunday through Saturday
result.Append(local.ToString("dddd", DateTimeFormatInfo.InvariantInfo));
break;
case 'L':
// Whether it's a leap year - 1 if it is a leap year, 0 otherwise.
result.Append(DateTime.IsLeapYear(local.Year) ? "1" : "0");
break;
case 'm':
// Numeric representation of a month, with leading zeros - 01 through 12
result.Append(local.ToString("MM", DateTimeFormatInfo.InvariantInfo));
break;
case 'M':
// A short textual representation of a month, three letters - Jan through Dec
result.Append(local.ToString("MMM", DateTimeFormatInfo.InvariantInfo));
break;
case 'n':
// Numeric representation of a month, without leading zeros - 1 through 12
result.Append(local.ToString("%M", DateTimeFormatInfo.InvariantInfo));
break;
case 'N':
// ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)
int day_of_week = (int)local.DayOfWeek;
result.Append(day_of_week == 0 ? 7 : day_of_week);
break;
case 'o':
{
// ISO-8601 year number. This has the same value as Y, except that if the ISO
// week number (W) belongs to the previous or next year, that year is used instead.
// (added in PHP 5.1.0)
int week, year;
GetIsoWeekAndYear(local, out week, out year);
result.Append(year);
break;
}
case 'O':
{
// Difference to Greenwich time (GMT) in hours Example: +0200
TimeSpan offset = zone.GetUtcOffset(local);
result.AppendFormat("{0}{1:00}{2:00}", (offset.Ticks < 0) ? "-" : "+", offset.Hours, offset.Minutes);
break;
}
case 'P':
{
// same as 'O' but with the extra colon between hours and minutes
// Difference to Greenwich time (GMT) in hours Example: +02:00
TimeSpan offset = zone.GetUtcOffset(local);
result.AppendFormat("{0}{1:00}:{2:00}", (offset.Ticks < 0) ? "-" : "+", offset.Hours, offset.Minutes);
break;
}
case 'r':
// RFC 822 formatted date Example: Thu, 21 Dec 2000 16:01:07 +0200
result.Append(local.ToString("ddd, dd MMM yyyy H:mm:ss ", DateTimeFormatInfo.InvariantInfo));
goto case 'O';
case 's':
// Seconds, with leading zeros - 00 through 59
result.Append(local.ToString("ss", DateTimeFormatInfo.InvariantInfo));
break;
case 'S':
result.Append(GetDayNumberSuffix(local.Day));
break;
case 't':
// Number of days in the given month 28 through 31
result.Append(DateTime.DaysInMonth(local.Year, local.Month));
break;
case 'T':
// Timezone setting of this machine Examples: EST, MDT ...
result.Append(zone.IsDaylightSavingTime(local) ? zone.DaylightName : zone.StandardName);
break;
case 'U':
// Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
result.Append(DateTimeUtils.UtcToUnixTimeStamp(utc));
break;
case 'u':
// Microseconds (added in PHP 5.2.2)
result.Append((utc.Millisecond / 1000).ToString("D6"));
break;
case 'w':
// Numeric representation of the day of the week - 0 (for Sunday) through 6 (for Saturday)
result.Append((int)local.DayOfWeek);
break;
case 'W':
{
// ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) Example: 42 (the 42nd week in the year)
int week, year;
GetIsoWeekAndYear(local, out week, out year);
result.Append(week);
break;
}
case 'y':
// A two digit representation of a year Examples: 99 or 03
result.Append(local.ToString("yy", DateTimeFormatInfo.InvariantInfo));
break;
case 'Y':
// A full numeric representation of a year, 4 digits Examples: 1999 or 2003
result.Append(local.ToString("yyyy", DateTimeFormatInfo.InvariantInfo));
break;
case 'z':
// The day of the year starting from 0
result.Append(local.DayOfYear - 1);
break;
case 'Z':
// TimeZone offset in seconds:
result.Append((int)zone.GetUtcOffset(local).TotalSeconds);
break;
case '\\':
// Escape char. Output next character directly to the result.
escape = true;
break;
default:
// unrecognized character, print it as-is.
result.Append(ch);
break;
}
}
if (escape)
result.Append('\\');
return result.ToString();
}
/// <summary>
/// Converts a given <see cref="DateTime"/> to the ISO week of year number and ISO year number.
/// </summary>
/// <param name="dt">The <see cref="DateTime"/>.</param>
/// <param name="week">The ISO week of year number.</param>
/// <param name="year">The ISO year number.</param>
private static void GetIsoWeekAndYear(DateTime dt, out int week, out int year)
{
int weekDay = (int)dt.DayOfWeek - 1; // Day of week (0 for Monday .. 6 for Sunday)
int yearDay = dt.DayOfYear; // Days since January 1st (1 .. 367)
int firstDay = (7 + weekDay - yearDay % 7 + 1) % 7; // Weekday of 1st January
if ((yearDay <= 7 - firstDay) && firstDay > 3)
{
// Week is a last year week (52 or 53)
week = (firstDay == 4 || (firstDay == 5 && DateTime.IsLeapYear(dt.Year - 1))) ? 53 : 52;
year = dt.Year - 1;
}
else if ((DateTime.IsLeapYear(dt.Year) ? 366 : 365) - yearDay < 3 - weekDay)
{
// Week is a next year week (1)
week = 1;
year = dt.Year + 1;
}
else
{
// Normal week
week = (yearDay + 6 - weekDay + firstDay) / 7;
if (firstDay > 3) week--;
year = dt.Year;
}
}
private static int GetSwatchBeat(DateTime utc)
{
int seconds = DateTimeUtils.UtcToUnixTimeStamp(utc);
int beat = (int)(((seconds - (seconds - ((seconds % 86400) + 3600))) * 10) / 864) % 1000;
return (beat < 0) ? beat + 1000 : beat;
}
/// <summary>
/// English ordinal suffix for the day of the month, 2 characters - st, nd, rd or th.
/// </summary>
/// <param name="DayNumber">Number of the day. In [1..31].</param>
/// <returns>st, nd, rd or th</returns>
private static string GetDayNumberSuffix(int DayNumber /* = 1..31 */)
{
Debug.Assert(DayNumber >= 1 && DayNumber <= 31);
int DayNumber10 = DayNumber % 10;
if (DayNumber10 == 1) { if (DayNumber/*%100*/ != 11) return "st"; }
else if (DayNumber10 == 2) { if (DayNumber/*%100*/ != 12) return "nd"; }
else if (DayNumber10 == 3) { if (DayNumber/*%100*/ != 13) return "rd"; }
return "th";
}
#endregion
#region strftime, gmstrftime
/// <summary>
/// Returns a string formatted according to the given format string using the current local time.
/// </summary>
/// <param name="format">Format of the string.</param>
/// <returns>Formatted string representing date and time.</returns>
[ImplementsFunction("strftime")]
public static string FormatTime(string format)
{
return FormatTime(format, DateTime.UtcNow, PhpTimeZone.CurrentTimeZone);
}
/// <summary>
/// Returns a string formatted according to the given format string using the given timestamp.
/// </summary>
/// <param name="format">Format of the string.</param>
/// <param name="timestamp">Number of seconds since 1970 representing the time to format.</param>
/// <returns>Formatted string representing date and time.</returns>
[ImplementsFunction("strftime")]
public static string FormatTime(string format, int timestamp)
{
return FormatTime(format, DateTimeUtils.UnixTimeStampToUtc(timestamp), PhpTimeZone.CurrentTimeZone);
}
/// <summary>