用Javascript显示周数?

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

<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代码。

只需将它添加到当前的代码中,然后调用(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> 

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

 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 (包括testing)

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

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

用法:

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

更多在这里: UI / Datepicker / iso8601Week

我意识到这不是一个通用的解决scheme,因为它会产生依赖性。 但是,考虑到jquery-ui的stream行,这可能只是一个简单的适合某人的东西 – 就像我一样。

它看起来像我在weeknumber.net发现这个function是相当准确和易于使用。

 // 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); } 

如果你像我一样幸运,需要find一个月的一周数字,稍作调整即可:

 // 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); } 

通过添加片段来扩展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()方法的脚本。

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

 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; }; 

如果您已经使用Angular,那么您可以获得$filter('date')

例如:

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

有了这个代码,你可以简单地;

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

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

如果你想要的东西是有效的,并且是面向未来的,可以使用像MomentJS这样的库。

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

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

我在这里看到的一些代码与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); } }; 

你可以find这个小提琴有用。 刚刚完成。 https://jsfiddle.net/dnviti/ogpt920w/下面的代码也是:;

 /** * 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); 
 *{ font-family: consolas } 
 <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> 

马丁·席林格的版本似乎是严格正确的。

因为我知道我只需要它在工作周的时间里正常工作,所以我使用这个更简单的表单,基于我在网上find的东西,不记得在哪里:

 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),但对其他所有事情都是正确的。

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

我忘记了什么被称为(Math.celi)所以我想更确定我是对的,并提出了这个代码。

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