像PHP一样使用JavaScript获取一年中的一周

像PHP一样使用JavaScript获取一年中的一周,javascript,date,Javascript,Date,如何获取当前一年的周数,比如PHP的date('W') 它应该是一年中的周数,从星期一开始的周数。您应该能够在这里得到您想要的东西: 在同一个网站上有一个更好的链接:与周一起工作 编辑 下面是一些基于提供的链接和Dommer早期发布的链接的代码。它已根据测试结果进行了轻微测试。请彻底测试,不提供任何保证 编辑2017 在实行夏时制期间的日期以及1月1日是星期五的年份存在问题。通过使用所有UTC方法修复。下面将向Moment.js返回相同的结果 /*对于给定日期,获取ISO周数 * *根据以下网

如何获取当前一年的周数,比如PHP的
date('W')


它应该是一年中的周数,从星期一开始的周数。

您应该能够在这里得到您想要的东西:

在同一个网站上有一个更好的链接:与周一起工作

编辑 下面是一些基于提供的链接和Dommer早期发布的链接的代码。它已根据测试结果进行了轻微测试。请彻底测试,不提供任何保证

编辑2017 在实行夏时制期间的日期以及1月1日是星期五的年份存在问题。通过使用所有UTC方法修复。下面将向Moment.js返回相同的结果

/*对于给定日期,获取ISO周数
*
*根据以下网址的信息:
*
*    http://www.merlyn.demon.co.uk/weekcalc.htm#WNR
*
*算法是找到最近的星期四,这是一年
*是一周中的年份编号。那就有几个星期
*从那一天到那一年的第一天。
*
*请注意,一年中的日期可以是上一年的几周
*或者明年,重叠时间最多为3天。
*
*例如,2014/12/29是2015年第1周的星期一
*2012年1月1日是2011年第52周的周日
*/
函数getWeekNumber(d){
//复制日期,以便不修改原始日期
d=新日期(Date.UTC(d.getFullYear(),d.getMonth(),d.getDate());
//设置为最近的星期四:当前日期+4-当前天数
//把星期天定为第七天
d、 setUTCDate(d.getUTCDate()+4-(d.getUTCDay()| | 7));
//一年中的第一天
var yearStart=新日期(Date.UTC(d.getUTCFullYear(),0,1));
//计算整周到最近的星期四
var weekNo=Math.ceil(((d-年初)/86400000)+1)/7);
//返回年和周数的数组
return[d.getUTCFullYear(),weekNo];
}
var结果=getWeekNumber(新日期());

document.write('It's current week'+结果[1]+'of'+结果[0])您应该能够在此处获得所需内容:

在同一个网站上有一个更好的链接:与周一起工作

编辑 下面是一些基于提供的链接和Dommer早期发布的链接的代码。它已根据测试结果进行了轻微测试。请彻底测试,不提供任何保证

编辑2017 在实行夏时制期间的日期以及1月1日是星期五的年份存在问题。通过使用所有UTC方法修复。下面将向Moment.js返回相同的结果

/*对于给定日期,获取ISO周数
*
*根据以下网址的信息:
*
*    http://www.merlyn.demon.co.uk/weekcalc.htm#WNR
*
*算法是找到最近的星期四,这是一年
*是一周中的年份编号。那就有几个星期
*从那一天到那一年的第一天。
*
*请注意,一年中的日期可以是上一年的几周
*或者明年,重叠时间最多为3天。
*
*例如,2014/12/29是2015年第1周的星期一
*2012年1月1日是2011年第52周的周日
*/
函数getWeekNumber(d){
//复制日期,以便不修改原始日期
d=新日期(Date.UTC(d.getFullYear(),d.getMonth(),d.getDate());
//设置为最近的星期四:当前日期+4-当前天数
//把星期天定为第七天
d、 setUTCDate(d.getUTCDate()+4-(d.getUTCDay()| | 7));
//一年中的第一天
var yearStart=新日期(Date.UTC(d.getUTCFullYear(),0,1));
//计算整周到最近的星期四
var weekNo=Math.ceil(((d-年初)/86400000)+1)/7);
//返回年和周数的数组
return[d.getUTCFullYear(),weekNo];
}
var结果=getWeekNumber(新日期());

document.write('It's current week'+结果[1]+'of'+结果[0])我发现Oracle规范中描述的Java SE的SimpleDataFormat类很有用: . 在我的谷歌应用程序脚本中,它是这样工作的:

function getWeekNumber() {
  var weekNum = parseInt(Utilities.formatDate(new Date(), "GMT", "w"));
  Logger.log(weekNum);
}
例如,在电子表格宏中,可以检索文件的实际时区:

function getWeekNumber() {
  var weekNum = parseInt(Utilities.formatDate(new Date(), SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone(), "w"));
  Logger.log(weekNum);
}

我发现Oracle规范中描述的Java SE的SimpleDataFormat类很有用: . 在我的谷歌应用程序脚本中,它是这样工作的:

function getWeekNumber() {
  var weekNum = parseInt(Utilities.formatDate(new Date(), "GMT", "w"));
  Logger.log(weekNum);
}
例如,在电子表格宏中,可以检索文件的实际时区:

function getWeekNumber() {
  var weekNum = parseInt(Utilities.formatDate(new Date(), SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone(), "w"));
  Logger.log(weekNum);
}
Jacob Wright的库以PHP函数的样式实现日期格式,并支持ISO-8601周数:

new Date().format('W');
对于一个星期数来说,这可能有点过头了,但它确实支持PHP样式的格式,而且如果您经常这样做,它会非常方便。

Jacob Wright的库以PHP函数的样式实现日期格式,并支持ISO-8601星期数:

new Date().format('W');
对于一个星期的数字来说,这可能有点过分,但它确实支持PHP风格的格式,而且如果你要做很多这方面的工作,它会非常方便。

一致地


不是ISO-8601周号,但如果搜索引擎将您指向此处。

如上所述,但无类别:

let now=new Date();
设onejan=newdate(now.getFullYear(),0,1);
week=Math.ceil(((now.getTime()-onejan.getTime())/86400000)+onejan.getDay()+1)/7);

控制台日志(周)不是ISO-8601周编号,而是搜索引擎是否将您指向此处。

如上所述,但无类别:

let now=new Date();
设onejan=newdate(now.getFullYear(),0,1);
week=Math.ceil(((now.getTime()-onejan.getTime())/86400000)+onejan.getDay()+1)/7);
控制台日志(周)这将“getWeek”方法添加到Date.prototype中,该方法返回年初的周数。争论定义了一周中的哪一天来考虑第一个问题。如果没有通过辩论,第一天假定为星期天

/**
 * Get week number in the year.
 * @param  {Integer} [weekStart=0]  First day of the week. 0-based. 0 for Sunday, 6 for Saturday.
 * @return {Integer}                0-based number of week.
 */
Date.prototype.getWeek = function(weekStart) {
    var januaryFirst = new Date(this.getFullYear(), 0, 1);
    if(weekStart !== undefined && (typeof weekStart !== 'number' || weekStart % 1 !== 0 || weekStart < 0 || weekStart > 6)) {
      throw new Error('Wrong argument. Must be an integer between 0 and 6.');
    }
    weekStart = weekStart || 0;
    return Math.floor((((this - januaryFirst) / 86400000) + januaryFirst.getDay() - weekStart) / 7);
};
/**
*获取一年中的周数。
*@param{Integer}[weekStart=0]一周的第一天。以0为基础。周日0,周六6。
*@return{Integer}0基于周数。
*/
Date.prototype.getWeek=函数(weekStart){
var一月一日=新
console.log(
    week(2016, 06, 11),//23
    week(2015, 9, 26),//39
    week(2016, 1, 1),//53
    week(2016, 1, 4),//1
    week(new Date(2016, 0, 4)),//1
    week("11 january 2016")//2
);
var myDate = new Date();
var myWeek = $filter('date')(myDate, 'ww');
/**
 * 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 1st
  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 week number is the number of weeks between the first Thursday of the year
  // and the Thursday in the target week (604800000 = 7 * 24 * 3600 * 1000)
  return 1 + Math.ceil((firstThursday - target) / 604800000);
}
function getWeek(date) {
  if (!(date instanceof Date)) date = new Date();

  // ISO week date weeks start on Monday, so correct the day number
  var nDay = (date.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
  date.setDate(date.getDate() - nDay + 3);

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

  // Set the target to the first Thursday of the year
  // First, set the target to January 1st
  date.setMonth(0, 1);

  // Not a Thursday? Correct the date to the next Thursday
  if (date.getDay() !== 4) {
    date.setMonth(0, 1 + ((4 - date.getDay()) + 7) % 7);
  }

  // The week number is the number of weeks between the first Thursday of the year
  // and the Thursday in the target week (604800000 = 7 * 24 * 3600 * 1000)
  return 1 + Math.ceil((n1stThursday - date) / 604800000);
}
getWeek(); // Returns 37 (or whatever the current week is)
getWeek(new Date('Jan 2, 2011')); // Returns 52
getWeek(new Date('Jan 1, 2016')); // Returns 53
getWeek(new Date('Jan 4, 2016')); // Returns 1
Date.prototype.getWeek = function(){

    // current week's Thursday
    var curWeek = new Date(this.getTime());
        curWeek.setDay(4);

    // Get year's first week's Thursday
    var firstWeek = new Date(curWeek.getFullYear(), 0, 4);
        firstWeek.setDay(4);

    return (curWeek.getDayIndex() - firstWeek.getDayIndex()) / 7 + 1;
};
/**
* Make a setDay() prototype for Date
* Sets week day for the date
*/
Date.prototype.setDay = function(day){

    // Get day and make Sunday to 7
    var weekDay = this.getDay() || 7;
    var distance = day - weekDay;
    this.setDate(this.getDate() + distance);

    return this;
}
/*
* Returns index of given date (from Jan 1st)
*/

Date.prototype.getDayIndex = function(){
    var start = new Date(this.getFullYear(), 0, 0);
    var diff = this - start;
    var oneDay = 86400000;

    return Math.floor(diff / oneDay);
};
now = new Date();
today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
firstOfYear = new Date(now.getFullYear(), 0, 1);
numOfWeek = Math.ceil((((today - firstOfYear) / 86400000)-1)/7);
// add get week prototype functions
// weeks always start from monday to sunday
// january 4th is always in the first week of the year
Date.prototype.getWeek = function () {
    year = this.getFullYear();
    var currentDotw = this.getWeekDay();
    if (this.getMonth() == 11 && this.getDate() - currentDotw > 28) {
        // if true, the week is part of next year 
        return this.getWeekForYear(year + 1);
    }
    if (this.getMonth() == 0 && this.getDate() + 6 - currentDotw < 4) {
        // if true, the week is part of previous year
        return this.getWeekForYear(year - 1);
    }
    return this.getWeekForYear(year);
}

// returns a zero based day, where monday = 0
// all weeks start with monday
Date.prototype.getWeekDay = function () {
    return  (this.getDay() + 6) % 7;
}

// corrected for summer/winter time
Date.prototype.getWeekForYear = function (year) {
    var currentDotw = this.getWeekDay();
    var fourjan = new Date(year, 0, 4);
    var firstDotw = fourjan.getWeekDay();
    var dayTotal = this.getDaysDifferenceCorrected(fourjan) // the difference in days between the two dates.
    // correct for the days of the week
    dayTotal += firstDotw; // the difference between the current date and the first monday of the first week, 
    dayTotal -= currentDotw; // the difference between the first monday and the current week's monday
    // day total should be a multiple of 7 now
    var weeknumber = dayTotal / 7 + 1; // add one since it gives a zero based week number.
    return weeknumber;
}

// corrected for timezones and offset
Date.prototype.getDaysDifferenceCorrected = function (other) {
    var millisecondsDifference = (this - other);
    // correct for offset difference. offsets are in minutes, the difference is in milliseconds
    millisecondsDifference += (other.getTimezoneOffset()- this.getTimezoneOffset()) * 60000;
    // return day total. 1 day is 86400000 milliseconds, floor the value to return only full days
    return Math.floor(millisecondsDifference / 86400000);
}
var runweekcompare = function(result, expected) {
    equal(result, expected,'Week nr expected value: ' + expected + ' Actual value: ' + result);
}

test('first week number test', function () {
    expect(5);
    var temp = new Date(2016, 0, 4); // is the monday of the first week of the year
    runweekcompare(temp.getWeek(), 1);
    var temp = new Date(2016, 0, 4, 23, 50); // is the monday of the first week of the year
    runweekcompare(temp.getWeek(), 1);
    var temp = new Date(2016, 0, 10, 23, 50); // is the sunday of the first week of the year
    runweekcompare(temp.getWeek(), 1);
    var temp = new Date(2016, 0, 11, 23, 50); // is the second week of the year
    runweekcompare(temp.getWeek(), 2);
    var temp = new Date(2016, 1, 29, 23, 50); // is the 9th week of the year
    runweekcompare(temp.getWeek(), 9);
});

test('first day is part of last years last week', function () {
    expect(2);
    var temp = new Date(2016, 0, 1, 23, 50); // is the first last week of the previous year
    runweekcompare(temp.getWeek(), 53);
    var temp = new Date(2011, 0, 2, 23, 50); // is the first last week of the previous year
    runweekcompare(temp.getWeek(), 52);
});

test('last  day is part of next years first week', function () {
    var temp = new Date(2013, 11, 30); // is part of the first week of 2014
    runweekcompare(temp.getWeek(), 1);
});

test('summer winter time change', function () {
    expect(2);
    var temp = new Date(2000, 2, 26); 
    runweekcompare(temp.getWeek(), 12);
    var temp = new Date(2000, 2, 27); 
    runweekcompare(temp.getWeek(), 13);
});

test('full 20 year test', function () {
    //expect(20 * 12 * 28 * 2);
    for (i = 2000; i < 2020; i++) {
        for (month = 0; month < 12; month++) {
            for (day = 1; day < 29 ; day++) {
                var temp = new Date(i, month, day);
                var expectedweek = temp.getWeek();
                var temp2 = new Date(i, month, day, 23, 50);
                var resultweek = temp.getWeek();
                equal(expectedweek, Math.round(expectedweek), 'week number whole number expected ' + Math.round(expectedweek) + ' resulted week nr ' + expectedweek);
                equal(resultweek, expectedweek, 'Week nr expected value: ' + expectedweek + ' Actual value: ' + resultweek + ' for year ' + i + ' month ' + month + ' day ' + day);
            }
        }
    }
});
Date.prototype.getWeek=function(){
    var date=new Date(this);
    date.setHours(0,0,0,0);
    return Math.round(((date.setDate(this.getDate()+2-(this.getDay()||7))-date.setMonth(0,4))/8.64e7+3+(date.getDay()||7))/7)+"/"+date.getFullYear();}
var yearStart = +new Date(d.getFullYear(), 0, 1);
var today = +new Date(d.getFullYear(),d.getMonth(),d.getDate());
var dayOfYear = ((today - yearStart + 1) / 86400000);
return Math.ceil(dayOfYear / 7).toString();
const formatter = d3.timeFormat('%U');
const weekNum = formatter(new Date());
import {DatePipe} from "@angular/common";

public rightWeekNum: number = 0;
  
constructor(private datePipe: DatePipe) { }
    
calcWeekOfTheYear(dateInput: Date) {
  let falseWeekNum = parseInt(this.datePipe.transform(dateInput, 'ww'));
  this.rightWeekNum = (dateInput.getDay() == 0) ? falseWeekNumber-1 : falseWeekNumber;
}