简体   繁体   中英

displaying the day of the week 3 days before today's date using javascript

I tried this javascript to display the day of the week from 3 days before the html page is accessed. It doesn't work when today is Sunday, Monday or Tuesday. (I think the problem is that the days are numbered 0-6 with no consideration of negative numbers in the line var date)

    var now = new Date();
    var days = new Array(
      'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
    var months = new Array(
      'January','February','March','April','May',
      'June','July','August','September','October',
      'November','December');
    var date = ((now.getDate()<10) ? "0" : "")+ now.getDate()-3;
    function fourdigits(number) {
      return (number < 1000) ? number + 1900 : number;}
    today =  days[now.getDay() -3] + ", " +
       months[now.getMonth()] + " " +
       date + ", " +
       (fourdigits(now.getYear()));
     document.write(today);

There are a number of issues with your code.

<SCRIPT LANGUAGE="JavaScript">

The language attribute for script elements was deprecated in HTML 4 and removed in subsequent versions.

<!--

HTML comment delimiters are tolerated at the start and end of script elements but should not be used. They have been unnecessary for 20 years.

var date = ((now.getDate()<10) ? "0" : "")+ now.getDate()-3;

When the date is 1 to 3, the first part of the expression will return a string like "0" or "". The second part will return a number from -2 to 0, so the result will be "0-2" to "00".

You can do something like:

var date = now.getDate();
date = (date < 10? '0' : '') + date;

Then there is:

today =  days[now.getDay() -3] + ", " +

getDay returns a number representing the day of the week, 0 for Sunday to 6 for Saturday, so from Sunday to Tuesday (day numbers 0–2) you'll be attempting to access a property of days that doesn't exist, which will return undefined .

   (fourdigits(now.getYear()));

getYear always returns the year less 1900. Use getFullYear instead.

See Where can I find documentation on formatting a date in JavaScript? and Add +1 to current date .

You should start by subtracting 3 days from the date, then format the result for output:

 var now = new Date(); now.setDate(now.getDate() - 3); var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday', 'Friday','Saturday']; var months = ['January','February','March','April','May','June','July', 'August','September','October','November','December']; var date = now.getDate(); date = (date < 10? "0" : "") + date; var today = days[now.getDay()] + ", " + months[now.getMonth()] + " " + date + ", " + now.getFullYear(); document.write(today); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM