gornvix
gornvix

Reputation: 3372

Convert client date / time string to JSON date / time string using JavaScript

I am trying to convert a client date / time string on a form into a JSON date / time string using JavaScript and moment (for a Django REST API back end). Here is what I have so far:

document.getElementById("dt_tm").value = 
moment(document.getElementById("inp-st").value, "DD/MM/YYYY HH:mm").toJSON();

Two problems with this:

  1. The date format cannot be hard coded as the client may have a different date format,
  2. moment adjusts the date / time and I don't need it to do that because the back end performs that function (using Django time zones).

So for example:

moment("14/05/2016 18:00", "DD/MM/YYYY HH:mm").toJSON() =
"2016-05-14T17:00:00.000Z"

When what I need is:

"2016-05-14T18:00"

(In this example my time zone is currently GMT+1.)

Upvotes: 0

Views: 692

Answers (1)

castletheperson
castletheperson

Reputation: 33476

If you would like toJSON to return the date in a different format, redefine moment.fn.toJSON to that it returns with your custom format instead of the default ISO8601 date format. This is outlined in the documentation.

moment.fn.toJSON = function() { 
    return this.format("YYYY-MM-DDTHH:mmZ"); 
};

Upvotes: 2

Related Questions