0
    var a = new Date;
    console.log(a.toJSON());

I want modify the Date.prototype.toJSON to increment the value of a by xxx minutes and after do what it do. I write this code but run in recursion:

    var Date_toJSON = Date.prototype.toJSON;
    Date.prototype.toJSON = function() {
        return Date_toJSON.call(new Date(this.getTime() + (60 * 1000)));
    }

I want to do this because JSON.strignify don' t count timezone differences. So, must modify Date.prototype.toJSON to change the (this) value by: (this.getTimezoneOffset() * 60 * 1000) (1 hour)eg.

Can somebody show me the right way to do this?

  • 3
    "*I want modify the Date.prototype.toJSON*" - [absolutely](https://stackoverflow.com/q/14034180/1048572) [don't!](https://stackoverflow.com/q/6223449/1048572) – Bergi Apr 29 '21 at 20:17
  • "*I write this code but run in recursion*" - it "works" fine for me, no recursion there. Can you post a [mcve] that causes an error, please? – Bergi Apr 29 '21 at 20:19
  • I must learn how to post a minimal reproducible example... – ΑΓΡΙΑ ΠΕΣΤΡΟΦΑ Apr 29 '21 at 21:58
  • ! You are right ! I modify the code and don't save the file... it works ! var Date_toJSON = Date.prototype.toJSON; Date.prototype.toJSON = function() { return Date_toJSON.call(new Date(this.getTime() - (this.getTimezoneOffset() * 60000) )); } Thank you Bergi, you wake up me! – ΑΓΡΙΑ ΠΕΣΤΡΟΦΑ Apr 29 '21 at 22:14

2 Answers2

1

Overwriting a prototype function is a bad practice Instead you can use a library like luxon or date-fns

https://moment.github.io/luxon/ https://date-fns.org/

Nrujal Sharma
  • 112
  • 1
  • 6
0

You can simply create your own CustomDate class extending the existing one.

In it you can overwrite toJSON(), and if you still need access to Date.prototype.toJSON() you can explicitly call it on super.

The example shows how to manipulate the return value of toJSON() and does explicity not try to implement the logic you need due to timezone related issues as that is not the focus of your question.

class CustomDate extends Date {
  toJSON() {
    return super.toJSON.call(new Date(this.getTime() + 60 * 1000))
  };
}
const a = new CustomDate;
console.log(a.toJSON());
connexo
  • 53,704
  • 14
  • 91
  • 128
  • Thank you connexo for the answer. In your example the super.toJSON() acts with a transparent way on a. a is the "this" . I want to modify the value of "this" before call super.. and not to add or subtract somethig on result of calling super.... is it possible? can change value of "this" before call super...? – ΑΓΡΙΑ ΠΕΣΤΡΟΦΑ Apr 29 '21 at 21:34
  • That would mean ruining the date (changing `this`) and also is not what your question asked. Edited a solution that preserves the Date yet makes `toJSON()` return what you need. – connexo Apr 29 '21 at 21:48
  • Yes, this is what realy want. Thank you connexo. – ΑΓΡΙΑ ΠΕΣΤΡΟΦΑ Apr 29 '21 at 22:46
  • @Bergi Sure, also that is closer to the original answer/intention. – connexo Apr 30 '21 at 06:01