DateConstructor.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using Jint.Native.Function;
  3. using Jint.Native.Object;
  4. using Jint.Runtime;
  5. using Jint.Runtime.Descriptors;
  6. namespace Jint.Native.Date
  7. {
  8. public sealed class DateConstructor : FunctionInstance, IConstructor
  9. {
  10. private readonly Engine _engine;
  11. public DateConstructor(Engine engine)
  12. : base(engine, new ObjectInstance(engine.Object), null, null, false)
  13. {
  14. _engine = engine;
  15. // the constructor is the function constructor of an object
  16. this.Prototype.DefineOwnProperty("constructor", new DataDescriptor(this) { Writable = true, Enumerable = false, Configurable = false }, false);
  17. this.Prototype.DefineOwnProperty("prototype", new DataDescriptor(Prototype) { Writable = true, Enumerable = false, Configurable = false }, false);
  18. }
  19. public override object Call(object thisObject, object[] arguments)
  20. {
  21. return Construct(arguments);
  22. }
  23. /// <summary>
  24. /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.3
  25. /// </summary>
  26. /// <param name="arguments"></param>
  27. /// <returns></returns>
  28. public ObjectInstance Construct(object[] arguments)
  29. {
  30. if (arguments.Length == 0)
  31. {
  32. return Construct(DateTime.UtcNow);
  33. }
  34. else if (arguments.Length == 1)
  35. {
  36. var v = TypeConverter.ToPrimitive(arguments[0]);
  37. if (TypeConverter.GetType(v) == TypeCode.String)
  38. {
  39. var d = DateTime.Parse(TypeConverter.ToString(v));
  40. return Construct(d);
  41. }
  42. v = TypeConverter.ToNumber(v);
  43. // todo: implement TimeClip
  44. return Construct(new DateTime(TypeConverter.ToUint32(v)));
  45. }
  46. else
  47. {
  48. var y = TypeConverter.ToNumber(arguments[0]);
  49. var m = TypeConverter.ToInteger(arguments[0]);
  50. var date = arguments.Length > 2 ? TypeConverter.ToInteger(arguments[2]) : 1;
  51. var hours = arguments.Length > 3 ? TypeConverter.ToInteger(arguments[3]) : 0;
  52. var minutes = arguments.Length > 4 ? TypeConverter.ToInteger(arguments[4]) : 0;
  53. var seconds = arguments.Length > 5 ? TypeConverter.ToInteger(arguments[5]) : 0;
  54. var ms = arguments.Length > 6 ? TypeConverter.ToInteger(arguments[6]) : 0;
  55. if ((!double.IsNaN(y)) && (0 <= TypeConverter.ToInteger(y)) && (TypeConverter.ToInteger(y) <= 99))
  56. {
  57. y += 1900;
  58. }
  59. return Construct(new DateTime((int) y, m + 1, date, hours, minutes, seconds, ms, DateTimeKind.Utc));
  60. }
  61. }
  62. public DateInstance Construct(DateTime value)
  63. {
  64. var instance = new DateInstance(Prototype);
  65. instance.PrimitiveValue = value;
  66. return instance;
  67. }
  68. }
  69. }