DayOfYearExpression.js 1.4 KB

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