0

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.)

gornvix
  • 3,154
  • 6
  • 35
  • 74

1 Answers1

2

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"); 
};
4castle
  • 32,613
  • 11
  • 69
  • 106
  • That solves my main problem. Although I still have the problem of switching to US date format on the client, I gave you the tick anyway. – gornvix May 10 '16 at 15:08
  • I think there should be a "Z" on the end of the format! – gornvix May 10 '16 at 15:13
  • Ok, I changed it. I don't know what that does exactly. Regarding the US date format, you can just use an if statement for "if the user is from the US, use the other format" – 4castle May 10 '16 at 16:41
  • You are probably interested in [this question](http://stackoverflow.com/q/25725882/5743988) if you want locale detection. – 4castle May 10 '16 at 16:48
  • The "Z" ensures the time zone information is preserved. – gornvix May 10 '16 at 17:15
  • Ah, gotcha. So for example, the output would be like `"2016-05-14T17:00+1:00"`? – 4castle May 10 '16 at 19:22