Hannah B. Hannah B. - 1 year ago 69
HTML Question

JavaScript date and time displaying wrong

I have a school project I'm doing in a web design class, and I never was good with JavaScript. I put the code in exactly as the book wanted, but it doesn't show up right.

Here's the code

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


It should display the time part as Tuesday, February 07, 2017 but instead shows 2/7/2017, 2017. Help please?

Answer Source

This one works perfectly.

        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>");

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download