DayOfYearExpression.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. // DEPENDENCIES
  14. var Expression = require("./Expression");
  15. // PROTOTYPE MEMBERS
  16. proto.getOpName = function getOpName(){
  17. return "$dayOfYear";
  18. };
  19. /**
  20. * Takes a date and returns the day of the year as a number between 1 and 366.
  21. * @method evaluate
  22. **/
  23. proto.evaluateInternal = function evaluateInternal(doc){
  24. //NOTE: the below silliness is to deal with the leap year scenario when we should be returning 366
  25. this.checkArgCount(1);
  26. var date = this.operands[0].evaluateInternal(doc);
  27. return klass.getDateDayOfYear(date);
  28. };
  29. // STATIC METHODS
  30. klass.getDateDayOfYear = function getDateDayOfYear(d){
  31. var y11 = new Date(d.getUTCFullYear(), 0, 1), // same year, first month, first day; time omitted
  32. ymd = new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()+1); // same y,m,d; time omitted, add 1 because days start at 1
  33. return Math.ceil((ymd - y11) / 86400000); //NOTE: 86400000 ms is 1 day
  34. };
  35. /** Register Expression */
  36. Expression.registerExpression("$dayOfYear",DayOfYearExpression.parse);