简体   繁体   中英

How to get date for specific weekday and then format

So I've been able to find the specific weekday date (the next upcoming Wednesday) I need with the following code:

var date = new Date();
date.setDate(date.getDate() + (3 - 1 - date.getDay() + 7) % 7 + 1);

However I'm now trying to format it in a way that suits me but I can't work out how. I tried this:

var date = new Date();
date.setDate(date.getDate() + (3 - 1 - date.getDay() + 7) % 7 + 1);
var day = date.getDay();
var monthNames = ["January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"];
var month = monthNames[date.getMonth()];
var year = date.getFullYear();
console.log(day, month, year);

But I get today's date again, I guess because I'm calling getDay/getMonth/getYear again. I just want to format the date returned to the 'date' variable but I can't work out how. I also don't understand how that date is calculated as I took it from another question which had no explanation.

I want it displayed as '10 February 2016' I don't want to use a library either.

you should use date.getDate() instead of date.getDay()

so your code should be

var day = date.getDate();

The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday.

Date.prototype.getDay()

Your expression to get the next Wednesday seems a bit convoluted, consider:

var x = 3 - date.getDay();
date.setDate(date.getDate() + (x > 0? x : 7 + x));

or if you really want to do it in one line:

date.setDate(date.getDate() + ((3 - date.getDay() + 7)%7 || 7));

If date is a Wednesday, this will return the next Wednesday (ie date plus 7 days).

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