Подтвердить что ты не робот

Показать номер недели с помощью Javascript?

У меня есть следующий код, который используется для отображения имени текущего дня, за которым следует заданная фраза.

<script type="text/javascript"> 
    <!-- 
    // Array of day names
    var dayNames = new Array(
    "It Sunday, the weekend is nearly over",
    "Yay! Another Monday",
     "Hello Tuesday, at least you're not Monday",
     "It Wednesday. Halfway through the week already",
     "It Thursday.",
     "It 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.

4b9b3361

Ответ 1

Просто добавьте его в свой текущий код, затем вызовите (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>

Ответ 2

Если вы уже используете jquery-ui (в частности, datepicker):

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

Использование:

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

Подробнее здесь: UI/Datepicker/iso8601Week

Я понимаю, что это не общее решение, поскольку оно несет зависимость. Однако, учитывая популярность jquery-ui, это может быть просто подходящим для кого-то - как это было для меня.

Ответ 3

Подумайте, используя мою реализацию "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 (включая тесты)

Ответ 4

Похоже, эта функция, которую я нашел в 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);
}

Ответ 5

Добавив фрагмент, вы расширяете объект 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

Все предлагаемые подходы могут давать неправильные результаты, потому что они не учитывают изменения в летнее/зимнее время. Вместо того, чтобы вычислять количество дней между двумя датами, используя константу 86400000 миллисекунд, лучше использовать такой подход, как следующий:

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

Если вы уже используете Angular, вы можете получить прибыль $filter('date').

Например:

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

Ответ 8

Если вы хотите что-то, что работает и является надежным, используйте библиотеку, например MomentJS.

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

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

Ответ 9

С помощью этого кода вы можете просто:

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

(Вам нужно будет вставить функцию getWeek над вашим текущим script)

Ответ 10

Некоторые из кода, который я вижу здесь , терпят неудачу с годами, такими как 2016, на этой неделе 53 переходит на вторую неделю.

Вот пересмотренная и рабочая версия:

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

Ответ 11

Вы можете найти эту скрипку полезной. Только что закончено. 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>

Ответ 12

Версия Мартина Шиллинджера является строго правильной.

Поскольку я знал, что мне нужно только правильно работать в рабочие дни недели, я пошел с этой более простой формой, основанной на том, что я нашел в Интернете, не помню, где:

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

Это не удается в начале января в дни, которые относятся к предыдущему году на прошлой неделе (он производит CW = 0 в этих случаях), но является правильным для всего остального.

Ответ 13

Я кодировал в темноте (вызов) и не мог найти или проверить свой код.

Я забыл, что было вызвано округлением (Math.celi). Поэтому я хотел быть уверенным, что правильно понял и придумал этот код.

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

console.log(week)