jQuery,格式日期没有显示正确的格式

时间:2017-11-26 15:45:05

标签: jquery date-format

我想显示所选月份第一天的日期,但日期格式并没有显示正确的格式。

我想像这样显示 01/11/2017 ,但它会显示如下

  

2017年11月1日星期三00:00:00 GMT + 0100(CET)

Select a Date: <input type="date" id="theDate" onmouseout="getTheDays()"/>
<p>First Day of the Month: <label id="fday"></label></p>
<p>Last Day of the Month: <label id="lday"></label></p>

<script>
    function getTheDays() {

        var dt = new Date($('#theDate').val());

        // GET THE MONTH AND YEAR OF THE SELECTED DATE.
        var month = dt.getMonth(),
            year = dt.getFullYear();

        // GET THE FIRST AND LAST DATE OF THE MONTH.
        var FirstDay = new Date(year, month, 1);
        var LastDay = new Date(year, month + 1, 0);

        // FINALLY, GET THE DAY.
        var weekday = new Array();
        weekday[0] = "Sunday";
        weekday[1] = "Monday";
        weekday[2] = "Tuesday";
        weekday[3] = "Wednesday";
        weekday[4] = "Thursday";
        weekday[5] = "Friday";
        weekday[6] = "Saturday";


        if (typeof weekday[FirstDay.getDay()] != 'undefined') {     // CHECK FOR 'undefined'.
            $('#fday').html(FirstDay.toString('dd-MM-yy'));
        }
        else {
            $('#fday').text('');
            $('#lday').text('');
        }
    }
</script>

1 个答案:

答案 0 :(得分:2)

我与您分享我们的toShortDate功能,您在这里:

function toShortDate(date) {
    if (!date) {
        return '--/--/--';
    }
    var d = new Date(Date.parse(date)),
        days = d.getDate(),
        month = (d.getMonth() + 1),
        finalDays = days < 10 ? '0' + days : '' + days,
        finalMonth = month < 10 ? '0' + month : '' + month;

    return finalDays +
        "/" + finalMonth +
        "/" + d.getFullYear().toString().substr(2, 2);
}

这个功能已经在生产中工作了一段时间,它完美地运行。祝你好运。