date.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. 'use strict';
  2. /**
  3. * Date class extension methods
  4. */
  5. var extensions = {
  6. addYear: function addYear() {
  7. this.setFullYear(this.getFullYear() + 1);
  8. },
  9. addMonth: function addMonth() {
  10. this.setDate(1);
  11. this.setHours(0);
  12. this.setMinutes(0);
  13. this.setSeconds(0);
  14. this.setMonth(this.getMonth() + 1);
  15. },
  16. addDay: function addDay() {
  17. var day = this.getDate();
  18. this.setDate(day + 1);
  19. this.setHours(0);
  20. this.setMinutes(0);
  21. this.setSeconds(0);
  22. if (this.getDate() === day) {
  23. this.setDate(day + 2);
  24. }
  25. },
  26. addHour: function addHour() {
  27. var hours = this.getHours();
  28. this.setHours(hours + 1);
  29. if (this.getHours() === hours) {
  30. this.setHours(hours + 2);
  31. }
  32. this.setMinutes(0);
  33. this.setSeconds(0);
  34. },
  35. addMinute: function addMinute() {
  36. this.setMinutes(this.getMinutes() + 1);
  37. this.setSeconds(0);
  38. },
  39. addSecond: function addSecond() {
  40. this.setSeconds(this.getSeconds() + 1);
  41. },
  42. toUTC: function toUTC() {
  43. var to = new CronDate(this);
  44. var ms = to.getTime() + (to.getTimezoneOffset() * 60000);
  45. to.setTime(ms);
  46. return to;
  47. }
  48. };
  49. /**
  50. * Extends Javascript Date class by adding
  51. * utility methods for basic date incrementation
  52. */
  53. function CronDate (timestamp) {
  54. var date = timestamp ? new Date(timestamp) : new Date();
  55. // Attach extensions
  56. var methods = Object.keys(extensions);
  57. for (var i = 0, c = methods.length; i < c; i++) {
  58. var method = methods[i];
  59. date[method] = extensions[method].bind(date);
  60. }
  61. return date;
  62. }
  63. module.exports = CronDate;