使用 javascript 检测每个月的最后一周

发布于 2024-09-03 12:40:54 字数 56 浏览 9 评论 0原文

javascript 中有什么方法可以检测每个(当前)月份的最后一周。还是这个月的最后一个星期一?

what would be a way in javascript to detect the last week of each (current) month. Or last monday of the month?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

梦途 2024-09-10 12:40:54

我建议获取该月的天数,然后从最后一天开始循环,直到 getDay() 返回星期一 (1) 或星期日 (0) .. 根据您一周的开始时间。一旦你得到开始日期......结束日期将是 startDate + 7 所以

我发现了这些内容 有帮助:

//Create a function that determines how many days in a month
//NOTE: iMonth is zero-based .. Jan is 0, Feb is 2 and so on ...
function daysInMonth(iMonth, iYear)
{
    return 32 - new Date(iYear, iMonth, 32).getDate();
}

然后循环:

//May - should return 31
var days_in_month = daysInMonth(4, 2010);

var weekStartDate = null;
var weekEndDate = null;    

for(var i=days_in_month; i>0; i--)
{
  var tmpDate = new Date(2010, 4, i);
  //week starting on sunday
  if(tmpDate.getDay() == 0)
  {
    weekStartDate = new Date(tmpDate);
    weekEndDate = new Date(tmpDate.setDate(tmpDate.getDate() + 6));
    //break out of the loop
    break; 
  }
}

I would suggest to get the number of days in the month and then loop from the last day until getDay() gives back a Monday (1) or Sunday(0) .. based on when does your week start. Once you get your start date ... end date would be startDate + 7 so something along these lines

I found this helpful :

//Create a function that determines how many days in a month
//NOTE: iMonth is zero-based .. Jan is 0, Feb is 2 and so on ...
function daysInMonth(iMonth, iYear)
{
    return 32 - new Date(iYear, iMonth, 32).getDate();
}

Then the loop:

//May - should return 31
var days_in_month = daysInMonth(4, 2010);

var weekStartDate = null;
var weekEndDate = null;    

for(var i=days_in_month; i>0; i--)
{
  var tmpDate = new Date(2010, 4, i);
  //week starting on sunday
  if(tmpDate.getDay() == 0)
  {
    weekStartDate = new Date(tmpDate);
    weekEndDate = new Date(tmpDate.setDate(tmpDate.getDate() + 6));
    //break out of the loop
    break; 
  }
}
梓梦 2024-09-10 12:40:54

使用 date 对象及其方法,您可以执行以下操作..

更新

到该月最后一个星期一的完整计算可以压缩为

var d = new Date();
d.setMonth( d.getMonth() + 1 );
d.setDate(0);
lastmonday = d.getDate() - (d.getDay() - 1);
alert(lastmonday);

详细的示例。

var now = new Date(); // get the current date

// calculate the last day of the month
if (now.getMonth() == 11 )  // if month is dec then go to next year and first month
{
    nextmonth = 0;
    nextyear = now.getFullYear() + 1;
}
else // otherwise go to next month of current year
{
  nextmonth = now.getMonth() + 1;
  nextyear = now.getFullYear();
}

var d = new Date( nextyear , nextmonth , 0); // setting day to 0 goes to last date of previous month
alert( d.getDay() ); // will alert the day of the week 0 being sunday .. you can calculate from there to get the first day of that week ..

Playing with the date object and its methods you can do the following..

update

the complete calculations to get to last monday of the month could be compacted to

var d = new Date();
d.setMonth( d.getMonth() + 1 );
d.setDate(0);
lastmonday = d.getDate() - (d.getDay() - 1);
alert(lastmonday);

verbose example..

var now = new Date(); // get the current date

// calculate the last day of the month
if (now.getMonth() == 11 )  // if month is dec then go to next year and first month
{
    nextmonth = 0;
    nextyear = now.getFullYear() + 1;
}
else // otherwise go to next month of current year
{
  nextmonth = now.getMonth() + 1;
  nextyear = now.getFullYear();
}

var d = new Date( nextyear , nextmonth , 0); // setting day to 0 goes to last date of previous month
alert( d.getDay() ); // will alert the day of the week 0 being sunday .. you can calculate from there to get the first day of that week ..
顾忌 2024-09-10 12:40:54

使用 getDay() 获取该月最后一天的星期几并从中进行计算(从该月的天数中减去该值应该可以解决问题。+/- 1) 。

Use getDay() to get the day of week of the last day in month and work from that (substracting the value from the number of days of the month should probably do the trick. +/- 1).

昇り龍 2024-09-10 12:40:54

要确定是否是星期一,请使用 .getDay() == 1。要确定是否是该月的最后一天,请添加 7 天并比较月份:nextMonday.setDate(monday.getDate()+7);
nextMonday.getMonth() == monday.getMonth();

To determine whether it is a Monday, use .getDay() == 1. To determine if it is the last of the month, add seven days and compare months: nextMonday.setDate(monday.getDate()+7);
nextMonday.getMonth() == monday.getMonth();

微暖i 2024-09-10 12:40:54

Javascript“Date”对象是你的朋友。

function lastOfThisMonth(whichDay) {
  var d= new Date(), month = d.getMonth();
  d.setDate(1); 
  while (d.getDay() !== whichDay) d.setDate(d.getDate() + 1);
  for (var n = 1; true; n++) {
    var nd = new Date(d.getFullYear(), month, d.getDate() + n * 7);
    if (nd.getMonth() !== month)
      return new Date(d.getFullYear(), month, d.getDate() + (n - 1) * 7).getDate();
  }
}

这将为您提供所选日期(0 到 7)所在月份最后一天的日期(月份中的日期,如 30)。

查找该月的最后将取决于您的意思。如果您指的是最后完整周,那么(如果您指的是星期日 - 星期六)找到最后一个星期六,然后减去 6。如果您指的是开始的最后一周月,找到最后一个星期日。

The Javascript "Date" object is your friend.

function lastOfThisMonth(whichDay) {
  var d= new Date(), month = d.getMonth();
  d.setDate(1); 
  while (d.getDay() !== whichDay) d.setDate(d.getDate() + 1);
  for (var n = 1; true; n++) {
    var nd = new Date(d.getFullYear(), month, d.getDate() + n * 7);
    if (nd.getMonth() !== month)
      return new Date(d.getFullYear(), month, d.getDate() + (n - 1) * 7).getDate();
  }
}

That'll give you the date (in the month, like 30) of the last day of the month that's the chosen day of the week (0 through 7).

Finding the last week of the month will depend on what you mean by that. If you mean the last complete week, then (if you mean Sunday - Saturday) find the last Saturday, and subtract 6. If you mean the last week that starts in the month, find the last Sunday.

嗳卜坏 2024-09-10 12:40:54

您可能还想查找给定日期之前或之后的第三个星期一或第一个星期二,
或标记两个日期之间的每周三。

Date.prototype.lastweek= function(wd, n){
    n= n || 1;
    return this.nextweek(wd, -n);
}
Date.prototype.nextweek= function(wd, n){
    if(n== undefined) n= 1;
    var incr= (n<0)? 1: -1,
    D= new Date(this),
    dd= D.getDay();
    if(wd=== undefined) wd= dd;
    if(dd!= wd) while(D.getDay()!= wd) D.setDate(D.getDate()+incr);
    D.setDate(D.getDate()+7*n);
    D.setHours(0, 0, 0, 0);
    return D;
}


function lastMondayinmonth(month, year){
    var day= new Date();
    if(!month) month= day.getMonth()+1;
    if(!year) year= day.getFullYear();
    day.setFullYear(year, month, 0);
    return day.lastweek(1);
}
alert(lastMondayinmonth())

You may also like to find the third Monday or the first Tuesday before or after a given date,
or flag every Wednesday between two dates.

Date.prototype.lastweek= function(wd, n){
    n= n || 1;
    return this.nextweek(wd, -n);
}
Date.prototype.nextweek= function(wd, n){
    if(n== undefined) n= 1;
    var incr= (n<0)? 1: -1,
    D= new Date(this),
    dd= D.getDay();
    if(wd=== undefined) wd= dd;
    if(dd!= wd) while(D.getDay()!= wd) D.setDate(D.getDate()+incr);
    D.setDate(D.getDate()+7*n);
    D.setHours(0, 0, 0, 0);
    return D;
}


function lastMondayinmonth(month, year){
    var day= new Date();
    if(!month) month= day.getMonth()+1;
    if(!year) year= day.getFullYear();
    day.setFullYear(year, month, 0);
    return day.lastweek(1);
}
alert(lastMondayinmonth())
淡墨 2024-09-10 12:40:54

我发现这样的示例可以检测每周的最后一个星期一,但它不会检测该月的最后一个星期一。也许这将有助于找到更好的解决方案,该代码看起来很短。

var dif, d = new Date(); // Today's date
dif = (d.getDay() + 6) % 7; // Number of days to subtract
d = new Date(d - dif * 24*60*60*1000); // Do the subtraction

alert(d); // Last monday.

i found such example that detects last monday of each week but it wont detect last monday of the month. maybe it will help to find better solution, that code looks short.

var dif, d = new Date(); // Today's date
dif = (d.getDay() + 6) % 7; // Number of days to subtract
d = new Date(d - dif * 24*60*60*1000); // Do the subtraction

alert(d); // Last monday.
染火枫林 2024-09-10 12:40:54

好的,到目前为止,我想出了这样的解决方案,使它有点像我自己的方式,并得到了这里提到的一些东西。它工作正常并且始终返回当月的最后一个星期一。

//function that will help to check how many days in month
function daysInMonth(iMonth, iYear)
{
    return 32 - new Date(iYear, iMonth, 32).getDate();
}


var dif = null;
d = new Date(); // Today's date
countDays = daysInMonth(d.getMonth(),d.getFullYear()); //Checking number of days in current month
d.setDate(countDays); //setting the date to last day of the month
dif = (d.getDay() + 6) % 7; // Number of days to subtract
d = new Date(d - dif * 24*60*60*1000); // Do the subtraction
alert(d.getDate()); //finally you get the last monday of the current month

OK, so far i came up with such solution making it a bit of my own way and getting a few things mentioned here. It works correct and always returns the last monday of current month.

//function that will help to check how many days in month
function daysInMonth(iMonth, iYear)
{
    return 32 - new Date(iYear, iMonth, 32).getDate();
}


var dif = null;
d = new Date(); // Today's date
countDays = daysInMonth(d.getMonth(),d.getFullYear()); //Checking number of days in current month
d.setDate(countDays); //setting the date to last day of the month
dif = (d.getDay() + 6) % 7; // Number of days to subtract
d = new Date(d - dif * 24*60*60*1000); // Do the subtraction
alert(d.getDate()); //finally you get the last monday of the current month
失与倦" 2024-09-10 12:40:54

获取该月的最后一天:

/**
 * Accepts either zero, one, or two parameters.
 *     If zero parameters: defaults to today's date
 *     If one parameter: Date object
 *     If two parameters: year, (zero-based) month
 */
function getLastDay() {
    var year, month;
    var lastDay = new Date();

    if (arguments.length == 1) {
        lastDay = arguments[0];
    } else if (arguments.length > 0) {
        lastDay.setYear(arguments[0]);
        lastDay.setMonth(arguments[1]);
    }

    lastDay.setMonth(lastDay.getMonth() + 1);
    lastDay.setDate(0);

    return lastDay;
}

获取最后一个星期一:

/**
 * Accepts same parameters as getLastDay()
 */
function getLastMonday() {
    var lastMonday = getLastDay.apply(this, arguments);
    lastMonday.setDate(lastMonday.getDate() - (lastMonday.getDay() == 0 ? 6 : (lastMonday.getDay() - 1)));
    return lastMonday;
}

获取给定日期的一年中的某一周:

/**
 * Accepts one parameter: Date object.
 * Assumes start of week is Sunday.
 */
function getWeek(d) {
    var jan1 = new Date(d.getFullYear(), 0, 1);
    return Math.ceil((((d - jan1) / (24 * 60 * 60 * 1000)) + jan1.getDay() + 1) / 7);
}

将它们放在一起(假设您正在使用 Firebug):

// Get the last day of August 2006:
var august2006 = new Date(2006, 7);
var lastDayAugust2006 = getLastDay(august2006);
console.log("lastDayAugust2006: %s", lastDayAugust2006);

// ***** Testing getWeek() *****
console.group("***** Testing getWeek() *****");
    // Get week of January 1, 2010 (Should be 1):
    var january12010Week = getWeek(new Date(2010, 0, 1));
    console.log("january12010Week: %s", january12010Week);

    // Get week of January 2, 2010 (Should still be 1):
    var january22010Week = getWeek(new Date(2010, 0, 2));
    console.log("january22010Week: %s", january22010Week);

    // Get week of January 3, 2010 (Should be 2):
    var january32010Week = getWeek(new Date(2010, 0, 3));
    console.log("january32010Week: %s", january32010Week);
console.groupEnd();
// *****************************

// Get the last week of this month:
var lastWeekThisMonth = getWeek(getLastDay());
console.log("lastWeekThisMonth: %s", lastWeekThisMonth);

// Get the last week of January 2007:
var lastWeekJan2007 = getWeek(getLastDay(2007, 0));
console.log("lastWeekJan2007: %s", lastWeekJan2007);

// Get the last Monday of this month:
var lastMondayThisMonth = getLastMonday();
console.log("lastMondayThisMonth: %s", lastMondayThisMonth);

// Get the week of the last Monday of this month:
var lastMondayThisMonthsWeek = getWeek(lastMondayThisMonth);
console.log("lastMondayThisMonthsWeek: %s", lastMondayThisMonthsWeek);

Get the last day of the month:

/**
 * Accepts either zero, one, or two parameters.
 *     If zero parameters: defaults to today's date
 *     If one parameter: Date object
 *     If two parameters: year, (zero-based) month
 */
function getLastDay() {
    var year, month;
    var lastDay = new Date();

    if (arguments.length == 1) {
        lastDay = arguments[0];
    } else if (arguments.length > 0) {
        lastDay.setYear(arguments[0]);
        lastDay.setMonth(arguments[1]);
    }

    lastDay.setMonth(lastDay.getMonth() + 1);
    lastDay.setDate(0);

    return lastDay;
}

Get the last Monday:

/**
 * Accepts same parameters as getLastDay()
 */
function getLastMonday() {
    var lastMonday = getLastDay.apply(this, arguments);
    lastMonday.setDate(lastMonday.getDate() - (lastMonday.getDay() == 0 ? 6 : (lastMonday.getDay() - 1)));
    return lastMonday;
}

Get week of the year for a given day:

/**
 * Accepts one parameter: Date object.
 * Assumes start of week is Sunday.
 */
function getWeek(d) {
    var jan1 = new Date(d.getFullYear(), 0, 1);
    return Math.ceil((((d - jan1) / (24 * 60 * 60 * 1000)) + jan1.getDay() + 1) / 7);
}

Putting them together (assuming you're using Firebug):

// Get the last day of August 2006:
var august2006 = new Date(2006, 7);
var lastDayAugust2006 = getLastDay(august2006);
console.log("lastDayAugust2006: %s", lastDayAugust2006);

// ***** Testing getWeek() *****
console.group("***** Testing getWeek() *****");
    // Get week of January 1, 2010 (Should be 1):
    var january12010Week = getWeek(new Date(2010, 0, 1));
    console.log("january12010Week: %s", january12010Week);

    // Get week of January 2, 2010 (Should still be 1):
    var january22010Week = getWeek(new Date(2010, 0, 2));
    console.log("january22010Week: %s", january22010Week);

    // Get week of January 3, 2010 (Should be 2):
    var january32010Week = getWeek(new Date(2010, 0, 3));
    console.log("january32010Week: %s", january32010Week);
console.groupEnd();
// *****************************

// Get the last week of this month:
var lastWeekThisMonth = getWeek(getLastDay());
console.log("lastWeekThisMonth: %s", lastWeekThisMonth);

// Get the last week of January 2007:
var lastWeekJan2007 = getWeek(getLastDay(2007, 0));
console.log("lastWeekJan2007: %s", lastWeekJan2007);

// Get the last Monday of this month:
var lastMondayThisMonth = getLastMonday();
console.log("lastMondayThisMonth: %s", lastMondayThisMonth);

// Get the week of the last Monday of this month:
var lastMondayThisMonthsWeek = getWeek(lastMondayThisMonth);
console.log("lastMondayThisMonthsWeek: %s", lastMondayThisMonthsWeek);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文