DayOfYearExpression.js 1.2 KB

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