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

6
  • JSON.stringify(new Date()) is "2016-05-10T14:27:19.698Z" if thats what your after Commented May 10, 2016 at 14:27
  • JSON.stringify appears to do the same thing as toJSON. Commented May 10, 2016 at 14:43
  • What do you mean by "cannot be hardcoded"? Wouldn't the format have to be hardcoded since it has to be sent as string? Commented May 10, 2016 at 14:52
  • I meant that the "DD/MM/YYYY" needs to change to "MM/DD/YYYY" on the client when in the US. Commented May 10, 2016 at 15:01
  • 1
    JSON date string should contain the zone info, otherwise it would be erroneous to convert it to Date object Commented May 10, 2016 at 15:06

1 Answer 1

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"); 
};
Sign up to request clarification or add additional context in comments.

6 Comments

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.
I think there should be a "Z" on the end of the format!
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"
You are probably interested in this question if you want locale detection.
The "Z" ensures the time zone information is preserved.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.