简体   繁体   中英

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;
};

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM