简体   繁体   中英

Display the name of the day 2 days ahead of current day

currently I'm doing a calender/scheduler. How do i display the name of the day that is 2 days ahead of the current day.(eg. today is wednesday so i'm suppose to display friday) Currently what i did was this.

var d=new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

var n = weekday[d.getDay()];

Demo FIDDLE

Jquery

    var d=new Date();
 d.setDate(d.getDate()+2);
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

alert(weekday[d.getDay()]);

Simply add +2 because getDay() returns the day.

var n = weekday[d.getDay()+2];

Here is the example Fiddle

In the following sample +d gives the same result as d.getTime() :

// 3600000ms (=1h) x 48 = 2 days
var n = weekday[new Date(+d + 3600000 * 48).getDay()]

I also really like ling.s's approach , but it needs a little fix :

// friday.getDay() -> 5
// weekday[5 + 2] -> undefined
// weekday[(5 + 2) % 7] -> "Sunday"
var n = weekday[(d.getDay() + 2) % 7];

Here is one way to display it :

<span id="twoDaysLater"></span>
var weekday = [
    'Sunday',
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday'
];

var now = new Date();
var twoDaysLater = new Date(+now + 3600000 * 48);
var dayName = weekday[twoDaysLater.getDay()];

jQuery(function ($) {
    // DOM is now ready
    $('#twoDaysLater').text(dayName);
});

Here is a demo : http://jsfiddle.net/wared/346L8/ .

Based on ling.s's solution : http://jsfiddle.net/wared/346L8/2/ .

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