1

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?

Hannah B.
  • 13
  • 3

3 Answers3

2

dateObj.toLocaleString accepts 2 parameters where you can set the Date format

    var today = new Date()
    var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
    console.log(today .toLocaleString('en-EN', options));
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30
0

Include //cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.js at the top of your page and then do the following to format your date

moment(new Date("March 21, 2017")).format("dddd, MMMM Do YYYY"); // Tuesday, March 21st 2017

Here is the

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

to moment doc for format

Tumen_t
  • 795
  • 5
  • 14
0

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>");
Sagar V
  • 12,158
  • 7
  • 41
  • 68