DayOfYearExpression.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. var DayOfYearExpression = module.exports = (function(){
  2. // CONSTRUCTOR
  3. /**
  4. * Get the DayOfYear from a date.
  5. *
  6. * @class DayOfYearExpression
  7. * @namespace munge.pipeline.expressions
  8. * @module munge
  9. * @constructor
  10. **/
  11. var klass = function DayOfYearExpression(){
  12. if(arguments.length !== 0) throw new Error("zero args expected");
  13. base.call(this);
  14. }, base = require("./NaryExpression"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  15. // PROTOTYPE MEMBERS
  16. proto.getOpName = function getOpName(){
  17. return "$dayOfYear";
  18. };
  19. proto.addOperand = function addOperand(expr) {
  20. this.checkArgLimit(1);
  21. base.prototype.addOperand.call(this, expr);
  22. };
  23. /**
  24. * Takes a date and returns the day of the year as a number between 1 and 366.
  25. * @method evaluate
  26. **/
  27. proto.evaluate = function evaluate(doc){
  28. //NOTE: the below silliness is to deal with the leap year scenario when we should be returning 366
  29. this.checkArgCount(1);
  30. var date = this.operands[0].evaluate(doc);
  31. return klass.getDateDayOfYear(date);
  32. };
  33. // STATIC METHODS
  34. klass.getDateDayOfYear = function getDateDayOfYear(d){
  35. var y11 = new Date(d.getFullYear(), 0, 1), // same year, first month, first day; time omitted
  36. ymd = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1); // same y,m,d; time omitted, add 1 because days start at 1
  37. return Math.ceil((ymd - y11) / 86400000); //NOTE: 86400000 ms is 1 day
  38. };
  39. return klass;
  40. })();