用Javascript显示周数?

时间:2011-10-14 09:38:26

标签: javascript date calendar

我有以下代码用于显示当天的名称,后跟一个设置短语。

<script type="text/javascript"> 
    <!-- 
    // Array of day names
    var dayNames = new Array(
    "It's Sunday, the weekend is nearly over",
    "Yay! Another Monday",
     "Hello Tuesday, at least you're not Monday",
     "It's Wednesday. Halfway through the week already",
     "It's Thursday.",
     "It's Friday - Hurray for the weekend",
    "Saturday Night Fever");
    var now = new Date();
    document.write(dayNames[now.getDay()] + ".");
     // -->
</script>

我想要做的是将当前的周数放在短语后的括号中。我找到了以下代码:

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(),0,1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
} 

这是从http://javascript.about.com/library/blweekyear.htm获取的,但我不知道如何将其添加到现有的JavaScript代码中。

13 个答案:

答案 0 :(得分:51)

只需将其添加到当前代码中,然后调用(new Date()).getWeek()

即可
<script>
    Date.prototype.getWeek = function() {
        var onejan = new Date(this.getFullYear(), 0, 1);
        return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
    }

    var weekNumber = (new Date()).getWeek();

    var dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    var now = new Date();
    document.write(dayNames[now.getDay()] + " (" + weekNumber + ").");
</script>

答案 1 :(得分:14)

如果你已经使用了jquery-ui(特别是datepicker):

Date.prototype.getWeek = function () { return $.datepicker.iso8601Week(this); }

用法:

var myDate = new Date();
myDate.getWeek();

更多信息: UI/Datepicker/iso8601Week

我意识到这不是一般解决方案,因为它会产生依赖性。然而,考虑到jquery-ui的流行,这可能只适合某人 - 就像我一样。

答案 2 :(得分:13)

考虑使用我的&#34; Date.prototype.getWeek&#34;的实现,认为比我在这里看到的其他人更准确:)

Date.prototype.getWeek = function(){
    // We have to compare against the first monday of the year not the 01/01
    // 60*60*24*1000 = 86400000
    // 'onejan_next_monday_time' reffers to the miliseconds of the next monday after 01/01

    var day_miliseconds = 86400000,
        onejan = new Date(this.getFullYear(),0,1,0,0,0),
        onejan_day = (onejan.getDay()==0) ? 7 : onejan.getDay(),
        days_for_next_monday = (8-onejan_day),
        onejan_next_monday_time = onejan.getTime() + (days_for_next_monday * day_miliseconds),
        // If one jan is not a monday, get the first monday of the year
        first_monday_year_time = (onejan_day>1) ? onejan_next_monday_time : onejan.getTime(),
        this_date = new Date(this.getFullYear(), this.getMonth(),this.getDate(),0,0,0),// This at 00:00:00
        this_time = this_date.getTime(),
        days_from_first_monday = Math.round(((this_time - first_monday_year_time) / day_miliseconds));

    var first_monday_year = new Date(first_monday_year_time);

    // We add 1 to "days_from_first_monday" because if "days_from_first_monday" is *7,
    // then 7/7 = 1, and as we are 7 days from first monday,
    // we should be in week number 2 instead of week number 1 (7/7=1)
    // We consider week number as 52 when "days_from_first_monday" is lower than 0,
    // that means the actual week started before the first monday so that means we are on the firsts
    // days of the year (ex: we are on Friday 01/01, then "days_from_first_monday"=-3,
    // so friday 01/01 is part of week number 52 from past year)
    // "days_from_first_monday<=364" because (364+1)/7 == 52, if we are on day 365, then (365+1)/7 >= 52 (Math.ceil(366/7)=53) and thats wrong

    return (days_from_first_monday>=0 && days_from_first_monday<364) ? Math.ceil((days_from_first_monday+1)/7) : 52;
}

您可以在此处查看我的公开回购https://bitbucket.org/agustinhaller/date.getweek(包含测试)

答案 3 :(得分:6)

我在weeknumber.net找到的这个功能看起来非常准确且易于使用。

// This script is released to the public domain and may be used, modified and
// distributed without restrictions. Attribution not necessary but appreciated.
// Source: http://weeknumber.net/how-to/javascript 

// Returns the ISO week of the date.
Date.prototype.getWeek = function() {
  var date = new Date(this.getTime());
  date.setHours(0, 0, 0, 0);
  // Thursday in current week decides the year.
  date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
  // January 4 is always in week 1.
  var week1 = new Date(date.getFullYear(), 0, 4);
  // Adjust to Thursday in week 1 and count number of weeks from date to week1.
  return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}

如果你像我一样幸运,需要找到一个月的周数,我会做一点调整:

// Returns the week in the month of the date.
Date.prototype.getWeekOfMonth = function() {
  var date = new Date(this.getTime());
  date.setHours(0, 0, 0, 0);
  // Thursday in current week decides the year.
  date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
  // January 4 is always in week 1.
  var week1 = new Date(date.getFullYear(), date.getMonth(), 4);
  // Adjust to Thursday in week 1 and count number of weeks from date to week1.
  return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}

答案 4 :(得分:6)

如果您想要一些有效并且面向未来的东西,请使用像MomentJS这样的库。

moment(date).week();
moment(date).isoWeek()

http://momentjs.com/docs/#/get-set/week/

答案 5 :(得分:3)

通过添加片段,您可以扩展Date对象。

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(),0,1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}

如果要在多个页面中使用它,可以将其添加到单独的js文件中,该文件必须先在其他脚本执行之前加载。对于其他脚本,我的意思是使用getWeek()方法的脚本。

答案 6 :(得分:3)

所有提议的方法可能会给出错误的结果,因为它们没有考虑夏季/冬季时间的变化。不是使用86'400'000毫秒的常数计算两个日期之间的天数,而是使用类似下面的方法:

getDaysDiff = function (dateObject0, dateObject1) {
    if (dateObject0 >= dateObject1) return 0;
    var d = new Date(dateObject0.getTime());
    var nd = 0;
    while (d <= dateObject1) {
        d.setDate(d.getDate() + 1);
        nd++;
    }
    return nd-1;
};

答案 7 :(得分:2)

如果你已经使用了Angular,那么你可以获利$filter('date')

例如:

var myDate = new Date();
var myWeek = $filter('date')(myDate, 'ww');

答案 8 :(得分:1)

使用该代码,您可以简单地;

document.write(dayNames[now.getDay()] + " (" + now.getWeek() + ").");

(您需要将getWeek函数粘贴到当前脚本之上)

答案 9 :(得分:0)

我在这里看到的一些代码失败与2016年一样,其中第53周跳到第2周。

以下是修订版和工作版:

Date.prototype.getWeek = function() { 

  // Create a copy of this date object  
  var target  = new Date(this.valueOf());  

  // ISO week date weeks start on monday, so correct the day number  
  var dayNr   = (this.getDay() + 6) % 7;  

  // Set the target to the thursday of this week so the  
  // target date is in the right year  
  target.setDate(target.getDate() - dayNr + 3);  

  // ISO 8601 states that week 1 is the week with january 4th in it  
  var jan4    = new Date(target.getFullYear(), 0, 4);  

  // Number of days between target date and january 4th  
  var dayDiff = (target - jan4) / 86400000;    

  if(new Date(target.getFullYear(), 0, 1).getDay() < 5) {
    // Calculate week number: Week 1 (january 4th) plus the    
    // number of weeks between target date and january 4th    
    return 1 + Math.ceil(dayDiff / 7);    
  }
  else {  // jan 4th is on the next week (so next week is week 1)
    return Math.ceil(dayDiff / 7); 
  }
}; 

答案 10 :(得分:0)

你会发现这个小提琴很有用。刚刚完成。 https://jsfiddle.net/dnviti/ogpt920w/ 以下代码也是:

&#13;
&#13;
/** 
 * Get the ISO week date week number 
 */  
Date.prototype.getWeek = function () {  
  // Create a copy of this date object  
  var target  = new Date(this.valueOf());  

  // ISO week date weeks start on monday  
  // so correct the day number  
  var dayNr   = (this.getDay() + 6) % 7;  

  // ISO 8601 states that week 1 is the week  
  // with the first thursday of that year.  
  // Set the target date to the thursday in the target week  
  target.setDate(target.getDate() - dayNr + 3);  

  // Store the millisecond value of the target date  
  var firstThursday = target.valueOf();  

  // Set the target to the first thursday of the year  
  // First set the target to january first  
  target.setMonth(0, 1);  
  // Not a thursday? Correct the date to the next thursday  
  if (target.getDay() != 4) {  
    target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);  
  }  

  // The weeknumber is the number of weeks between the   
  // first thursday of the year and the thursday in the target week  
  return 1 + Math.ceil((firstThursday - target) / 604800000); // 604800000 = 7 * 24 * 3600 * 1000  
}  

/** 
* Get the ISO week date year number 
*/  
Date.prototype.getWeekYear = function ()   
{  
  // Create a new date object for the thursday of this week  
  var target  = new Date(this.valueOf());  
  target.setDate(target.getDate() - ((this.getDay() + 6) % 7) + 3);  

  return target.getFullYear();  
}

/** 
 * Convert ISO week number and year into date (first day of week)
 */ 
var getDateFromISOWeek = function(w, y) {
  var simple = new Date(y, 0, 1 + (w - 1) * 7);
  var dow = simple.getDay();
  var ISOweekStart = simple;
  if (dow <= 4)
    ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
  else
    ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
  return ISOweekStart;
}

var printDate = function(){
  /*var dateString = document.getElementById("date").value;
	var dateArray = dateString.split("/");*/ // use this if you have year-week in the same field

  var dateInput = document.getElementById("date").value;
  if (dateInput == ""){
    var date = new Date(); // get today date object
  }
  else{
    var date = new Date(dateInput); // get date from field
  }

  var day = ("0" + date.getDate()).slice(-2); // get today day
  var month = ("0" + (date.getMonth() + 1)).slice(-2); // get today month
  var fullDate = date.getFullYear()+"-"+(month)+"-"+(day) ; // get full date
  var year = date.getFullYear();
  var week = ("0" + (date.getWeek())).slice(-2);
  var locale= "it-it";
  
  document.getElementById("date").value = fullDate; // set input field

  document.getElementById("year").value = year;
  document.getElementById("week").value = week; // this prototype has been written above

  var fromISODate = getDateFromISOWeek(week, year);
  
	var fromISODay = ("0" + fromISODate.getDate()).slice(-2);
  var fromISOMonth = ("0" + (fromISODate.getMonth() + 1)).slice(-2);
  var fromISOYear = date.getFullYear();
  
  // Use long to return month like "December" or short for "Dec"
  //var monthComplete = fullDate.toLocaleString(locale, { month: "long" }); 

  var formattedDate = fromISODay + "-" + fromISOMonth + "-" + fromISOYear;

  var element = document.getElementById("fullDate");

  element.value = formattedDate;
}

printDate();
document.getElementById("convertToDate").addEventListener("click", printDate);
&#13;
*{
  font-family: consolas
}
&#13;
<label for="date">Date</label>
<input type="date" name="date" id="date" style="width:130px;text-align:center" value="" />
<br /><br />
<label for="year">Year</label>
<input type="year" name="year" id="year" style="width:40px;text-align:center" value="" />
-
<label for="week">Week</label>
<input type="text" id="week" style="width:25px;text-align:center" value="" />
<br /><br />
<label for="fullDate">Full Date</label>
<input type="text" id="fullDate" name="fullDate" style="width:80px;text-align:center" value="" />
<br /><br />
<button id="convertToDate">
Convert Date
</button>
&#13;
&#13;
&#13;

它是纯粹的JS。 里面有很多日期函数,允许你将日期转换为周数,反之亦然:)

答案 11 :(得分:0)

Martin Schillinger的版本似乎是严格正确的版本。

因为我知道我只需要在工作周工作时才能正常工作,所以我选择了这种简单的形式,基于我在网上找到的东西,不记得在哪里:

ISOWeekday = (0 == InputDate.getDay()) ? 7 : InputDate.getDay();
ISOCalendarWeek = Math.floor( ( ((InputDate.getTime() - (new Date(InputDate.getFullYear(),0,1)).getTime()) / 86400000) - ISOWeekday + 10) / 7 );

它在1月初在上一周属于上一年的日子里失败了(在那些情况下它产生了CW = 0),但对其他一切都是正确的。

答案 12 :(得分:0)

我在黑暗中编码(挑战),无法查找或测试我的代码。

我忘了叫什么回合(Math.celi)所以我想要更加确定我做对了并想出了这段代码。

var elm = document.createElement('input')
elm.type = 'week'
elm.valueAsDate = new Date()
var week = elm.value.split('W').pop()

console.log(week)
只是证明你如何以任何其他方式获得本周的概念

但我仍然建议使用DOM不需要的任何其他解决方案。