How to get first date and last date of the week from week number and year?

前端 未结 4 476
滥情空心
滥情空心 2021-01-05 01:11

In JavaScript I want to get first date of the week and last date of the week by week number and year only.

For example if I my input is:

2(week),2012

相关标签:
4条回答
  • 2021-01-05 01:42

    A little change to @bardiir 's answer, if the first day of the year is not Sunday(or Monday) that result is not correct. You should minus the number of the first day.

    Changed code

    firstDay = new Date(2015, 0, 1).getDay();
    console.log(firstDay);
    var year = 2015;
    var week = 67;
    var d = new Date("Jan 01, " + year + " 01:00:00");
    var w = d.getTime() - (3600000 * 24 * (firstDay - 1)) + 604800000 * (week - 1)
    var n1 = new Date(w);
    var n2 = new Date(w + 518400000)
    
    console.log(n1);
    console.log(n2);

    if you wish the first is Sunday, change (firstDay-1) to firstDay

    0 讨论(0)
  • 2021-01-05 01:49

    Try this:

    var year = 2012;
    var week = 2;
    var d = new Date("Jan 01, " + year + " 01:00:00");
    var w = d.getTime() + 604800000 * (week - 1);
    var n1 = new Date(w);
    var n2 = new Date(w + 518400000)
    
    console.log(n1);
    console.log(n2);

    n1 contains the first day of the week
    n2 contains the last day of the week

    As for the constants:
    604800000 is one week in milliseconds
    518400000 is six days

    0 讨论(0)
  • 2021-01-05 01:49

    you can check and try with below link.

    How to get first and last day of the week in JavaScript

    It will may helpful to you.

    Thanks.

    0 讨论(0)
  • 2021-01-05 01:59
       dt = new Date();
       var firstDateOfWeek=(dt.setDate(dt.getDate()-dt.getDay()));
       var lastDateOfWeek=(dt.setDate(dt.getDate()+6-dt.getDay()));
    
    0 讨论(0)
提交回复
热议问题