DayOfYearExpression.js 1.5 KB

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