DayOfYearExpression.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. /** Takes a date and returns the day of the year as a number between 1 and 366. **/
  24. proto.evaluate = function evaluate(doc){
  25. //NOTE: the below silliness is to deal with the leap year scenario when we should be returning 366
  26. this.checkArgCount(1);
  27. var date = this.operands[0].evaluate(doc);
  28. return klass.getDateDayOfYear(date);
  29. };
  30. // STATIC METHODS
  31. klass.getDateDayOfYear = function getDateDayOfYear(d){
  32. var y11 = new Date(d.getFullYear(), 0, 1), // same year, first month, first day; time omitted
  33. ymd = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1); // same y,m,d; time omitted, add 1 because days start at 1
  34. return Math.ceil((ymd - y11) / 86400000); //NOTE: 86400000 ms is 1 day
  35. };
  36. return klass;
  37. })();