DayOfYearExpression.js 1.5 KB

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