将日期转换为YYYY-MM-DD

时间:2016-10-19 22:32:14

标签: javascript jquery html date

我有一个适用于所有浏览器的输入日期类型(适用于Chrome的HTML5,以及一些可在IE11和Firefox中使用的javascript)。

<input type="date" name="Date" id="Date" min="2016-10-19" max="2016-11-03"/>

但是发生了一件奇怪的事情。如果我在Chrome中选择了一个日期,它就会发布到我的数据库中,但是如果我在IE11或Firefox中选择一个日期,它将被拒绝为无效格式。

My Scripts目前在HTML中,这就是为什么它看起来像这样:

        <script type="text/javascript">
        var datefield=document.createElement("input")
        datefield.setAttribute("type", "date")
        if (datefield.type!="date"){ //if browser doesn't support input type="date", load files for jQuery UI Date Picker
            document.write('<link href="css/jquery-ui.css" rel="stylesheet" type="text/css" />\n')
            document.write('<script src="scripts/jquery.min.js"><\/script>\n')
            document.write('<script src="scripts/jquery-ui.min.js"><\/script>\n')
        }
    </script>
    <script type="text/javascript">
        if (datefield.type!="date"){ //if browser doesn't support input type="date", initialize date picker widget:
            jQuery(function($){ //on document.ready
                $('#Date').datepicker({
                    showOtherMonths: true,
                    selectOtherMonths: true,
                    changeMonth: true,
                    minDate: '10/19/2016',
                    maxDate: '11/03/2016',
                });
            })
        }
    </script>

1 个答案:

答案 0 :(得分:0)

GOT IT! Had to add the dateFormat property and orient the yy-mm-dd the way my database needed it. I assume you can change it to dd/mm/yy or yy/mm/dd, however you need it arranged.

<script type="text/javascript">
        if (datefield.type!="date"){ //if browser doesn't support input type="date", initialize date picker widget:
            jQuery(function($){ //on document.ready
                $('#Date').datepicker({
                    dateFormat: 'yy-mm-dd',
                    showOtherMonths: true,
                    selectOtherMonths: true,
                    changeMonth: true,
                    minDate: '2016-10-19',
                    maxDate: '2016-11-03'
                });
            })
        }
    </script>