gornvix
gornvix

Reputation: 3372

How do I get this JavaScript / moment code to work with both US and UK date formats?

How do I get this JavaScript / moment code to work with both US (MM/DD/YYYY) and UK (DD/MM/YYYY) date formats? Currently it only works with a UK format:

moment.fn.toJSON = function() { 
    return this.format("YYYY-MM-DDTHH:mmZ"); 
};
function submitform() {
    document.getElementById("st_dt_tm").value = 
moment(document.getElementById("inp-st").value, "DD/MM/YYYY HH:mm").toJSON();
        return true;
};

Upvotes: 0

Views: 100

Answers (1)

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

There is no way, by date format alone, to know if it is DD/MM/YYYY or MM/DD/YYYY because of dates like 01/02/2016, which is a valid (but different) date either way.

Your choices are:

Use MM/DD/YYYY for US dates and DD-MM-YYYY for European dates, which is similar to what the JavaScript Date object does, but even that is not entirely useful -- more details here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

The "best" option is to use some kind of cultural indicator flag -- either something passed in from the back-end code, or perhaps asking JavaScript to format a date for you and looking at what format they use -- and changing strings accordingly.

Upvotes: 1

Related Questions