JavaScript日期和时间显示错误

时间:2017-02-07 14:32:45

标签: javascript html html5

我有一个我在网页设计课上做的学校项目,我从来没有用过JavaScript。我完全按照本书的要求编写了代码,但它并没有正确显示。

这是代码

<script type="text/javascript">
<!--Hide from old browsers
    var today = new Date()
    var dayofweek = today.toLocaleString()
    dayLocate = dayofweek.indexOf(" ")
    weekDay = dayofweek.substring(0, dayLocate)
    newDay = dayofweek.substring(dayLocate)
    dateLocate = newDay.indexOf(",")
    monthDate = newDay.substring(0, dateLocate+1)
    yearLocate = dayofweek.indexOf("2017")
    year = dayofweek.substr(yearLocate, 4)

    var springDate = new Date("March 21, 2017")
    var daysToGo = springDate.getTime()-today.getTime()
    var daysToSpring = Math.ceil(daysToGo/(1000*60*60*24))

    document.write("<p style='margin-left:10%; font-family:Arial,sans-serif; font-weight:bold; font-size:14'>Today is "+weekDay+" "+monthDate+" "+year+", that leaves only "+daysToSpring+" days until the start of spring.")
    document.write("<br />Spring is the time to prepare your landscape for new growth of flowers and lawns. ")
    document.write("<br /> Call us now at (221) 555-9100 for a free consultation and free estimate.</p>")

    //-->
    </script>

它应该显示时间部分为2017年2月7日星期二,而是显示2017年2月7日,2017年。请帮忙吗?

3 个答案:

答案 0 :(得分:2)

dateObj.toLocaleString接受2 parameters,您可以在其中设置日期格式

&#13;
&#13;
    var today = new Date()
    var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
    console.log(today .toLocaleString('en-EN', options));
&#13;
&#13;
&#13;

答案 1 :(得分:0)

在页面顶部添加//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.js,然后执行以下操作来格式化日期

moment(new Date("March 21, 2017")).format("dddd, MMMM Do YYYY"); // 2017年3月21日星期二

这是

http://momentjs.com/docs/#/displaying/format/

format

的时刻文档

答案 2 :(得分:0)

这个完美无缺。

&#13;
&#13;
        var today = new Date();
        var dayofweek = today.toUTCString();
        dayofweek = dayofweek.substring(0,dayofweek.indexOf(':')-3);
    
        var springDate = new Date("March 21, 2017");
        var daysToGo = springDate.getTime()-today.getTime();
        var daysToSpring = Math.ceil(daysToGo/(1000*60*60*24));
    
        document.write("<p style='margin-left:10%; font-family:Arial,sans-serif; font-weight:bold; font-size:14'>Today is "+dayofweek+", that leaves only "+daysToSpring+" days until the start of spring.");
        document.write("<br />Spring is the time to prepare your landscape for new growth of flowers and lawns. ");
        document.write("<br /> Call us now at (221) 555-9100 for a free consultation and free estimate.</p>");
&#13;
&#13;
&#13;