3

I'm trying to extend moment's toString function to return the date in a different format.

I.e. I want to create momentDate as below:

// Will return "Sat Dec 12 2015 00:00:00 GMT+1100"
moment('2015-12-12').toString();

// Will return a custom format, e.g. "2015-12-12"
momentDate('2015-12-12').toString();

I've been trying with no success. I'm not sure if it's even possible because of how moment is written so I thought I would ask here.

Jeremy
  • 91
  • 1
  • 7
  • You have to override the toString() to return what you want it to return – myselfmiqdad Jan 06 '16 at 04:22
  • Try to understand [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString) in `JavaScript`. – piglovesx Jan 06 '16 at 04:43
  • @piglovesx, moment is a function which is why I'm having a hard time! It's toString function definition can be found by looking at moment.prototype.constructor.fn.toString, I haven't had any success in trying to override this. I've tried to create a class and override this (similar to what is done in this comment http://stackoverflow.com/a/11542872/2248573) without much success. moment.toString() keeps getting modified too! – Jeremy Jan 06 '16 at 05:24
  • Possible duplicate of [How do I extend (with a new name) a static function in javascript without affecting the original?](https://stackoverflow.com/questions/34626229/how-do-i-extend-with-a-new-name-a-static-function-in-javascript-without-affect) – gogaz Sep 22 '18 at 23:49

1 Answers1

2

My question was answered here:

https://stackoverflow.com/a/34626333/2248573

Note: Solution works for v2.11.0.

function extendedMoment() {
  var self = moment();
  
  self.__proto__ = extendedMoment.prototype;
  
  return self;
}

extendedMoment.prototype.__proto__ = moment.prototype;

extendedMoment.prototype.toString = function(){
  return this.format('YYYY-MM-DD')
}

document.write("Original: " + moment().toString());
document.write("<br/>");
document.write("Extended: " + extendedMoment().toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.0/moment.js"></script>
Community
  • 1
  • 1
Jeremy
  • 91
  • 1
  • 7