DateInstance.cs 1.6 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 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. PrimitiveValue = double.NaN;
  17. }
  18. public DateTime ToDateTime()
  19. {
  20. if (DateTimeRangeValid)
  21. {
  22. return DateConstructor.Epoch.AddMilliseconds(PrimitiveValue);
  23. }
  24. ExceptionHelper.ThrowRangeError(_engine.Realm);
  25. return DateTime.MinValue;
  26. }
  27. public double PrimitiveValue { get; set; }
  28. internal bool DateTimeRangeValid => !double.IsNaN(PrimitiveValue) && PrimitiveValue <= Max && PrimitiveValue >= Min;
  29. public override string ToString()
  30. {
  31. if (double.IsNaN(PrimitiveValue))
  32. {
  33. return "NaN";
  34. }
  35. if (double.IsInfinity(PrimitiveValue))
  36. {
  37. return "Infinity";
  38. }
  39. return ToDateTime().ToString("ddd MMM dd yyyy HH:mm:ss 'GMT'K", CultureInfo.InvariantCulture);
  40. }
  41. }
  42. }