简体   繁体   中英

Simple way to show the current week using jquery

I need to have a script on a page which dynamically changes the current week. I need to have the show "Week of February 15, 2010.

After next Sunday, I'd like the page to say "Week of February 22, 2010". I picked Monday for the display day but it could easily be Sunday.

Any suggestions are much appreciated!.

No jQuery inherently required.

var date = new Date();
var dayOfWeek = date.getDay();
date.setTime(date.getTime() - dayOfWeek*86400000); // 86 400 000 = # MS per day
alert('Week of ' + date.toLocaleFormat('%B %e, %Y') + '.'); // toLocaleFormat is a non-standard method

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Date

jQuery is needed maybe just to easily show the result, but date functions are core javascript:

var date = new Date();
while (date.getDate() != 1 /* Monday */) {
    date.setDate(date.getDate() - 1);
}
var months = new Array("January", "February", "March", "April", 
                       "May", "June", "July", "August", "September", 
                        "October", "November", "December");

$("#some-id").val("Week of " + months[date.getMonth()] + " " +
                  date.getDate() + ", " + date.getFullYear());

var d=new Date();
var m=new Date(d.getTime() - 24*60*60*1000*d.getDay())
document.write(m);

m contains date of Sunday of this week.

Try this:

const getCurrentWeek = (function() {
    let fdWeek = new Date();
    let dia = fdWeek.getDay();
    let firtDay = new Date();
    firtDay.setTime(fdWeek.setUTCHours(-((dia) * 24)));
    let lastDay = new Date();
    lastDay.setTime(fdWeek.setUTCHours(6 * 24));
    let week = {
        firtDay : firtDay,
        lastDay : lastDay
    }
    return week;
});

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