DateInstance.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Globalization;
  3. using Jint.Native.Object;
  4. using Jint.Runtime;
  5. namespace Jint.Native.Date
  6. {
  7. public sealed class DateInstance : ObjectInstance
  8. {
  9. // Maximum allowed value to prevent DateTime overflow
  10. private static readonly double Max = (DateTime.MaxValue - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
  11. // Minimum allowed value to prevent DateTime overflow
  12. private static readonly double Min = -(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc) - DateTime.MinValue).TotalMilliseconds;
  13. public DateInstance(Engine engine)
  14. : base(engine, ObjectClass.Date)
  15. {
  16. DateValue = double.NaN;
  17. }
  18. public DateTime ToDateTime()
  19. {
  20. if (DateTimeRangeValid)
  21. {
  22. return DateConstructor.Epoch.AddMilliseconds(DateValue);
  23. }
  24. ExceptionHelper.ThrowRangeError(_engine.Realm);
  25. return DateTime.MinValue;
  26. }
  27. public double DateValue { get; internal set; }
  28. internal bool DateTimeRangeValid => !double.IsNaN(DateValue) && DateValue <= Max && DateValue >= Min;
  29. public override string ToString()
  30. {
  31. if (double.IsNaN(DateValue))
  32. {
  33. return "NaN";
  34. }
  35. if (double.IsInfinity(DateValue))
  36. {
  37. return "Infinity";
  38. }
  39. return ToDateTime().ToString("ddd MMM dd yyyy HH:mm:ss 'GMT'zzz", CultureInfo.InvariantCulture);
  40. }
  41. }
  42. }