如何通过javascript

时间:2016-03-09 17:13:54

标签: javascript jquery getdate

我想要一个javascript函数,它将start_date作为上周星期一日期,将end_date作为上周星期日。 例如,今天是03/09/2016,所以我想要 start_date = 02/29/2016 end_date = 03/06/2016

到目前为止,我已将代码视为

        function GetLastWeekDate(){
        start_date = new Date();
        start_date.setHours(0,0,0,0);
        end_date = new Date();
        var date=null;
        var curr = date ? new Date(date) : new Date();
        var first = curr.getDate() - curr.getDay("monday"),
             last  = first + 6;

         start_date.setDate( first );
         end_date. setDate( last );
         }


(function() {
     var original = Date.prototype.getDay;
    var daysOfWeek = {
    sunday: 0,
    monday: 1,
    tuesday: 2,
    wednesday: 3,
    thursday: 4,
    friday: 5,
    saturday: 6,
    };

     Date.prototype.getDay = function(weekBegins) {
      weekBegins = (weekBegins || "sunday").toLowerCase();
        return (original.apply(this) + 7 - daysOfWeek[weekBegins]) % 7;
      };
    })();

但它给我的日期为

    03/07/2016 and 03/13/2016

如何解决此问题以获取我想要的日期?

2 个答案:

答案 0 :(得分:2)

如果您要处理大量日期,我强烈建议您使用moment.js库。

在这种情况下,日期将是:

var startDate = moment().subtract(1, 'week').startOf('week');
var endDate = moment().subtract(1, 'week').endOf('week');

在这里你可以看到它的实际效果:

document.addEventListener('DOMContentLoaded', function() {
  document.getElementById("fromDate").textContent = moment().subtract(1, "week").startOf("week");
  document.getElementById("toDate").textContent = moment().subtract(1, "week").endOf("week");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script>
<html>
  <body>
    <p>From : <span id="fromDate"></span></p>
    <p>To : <span id="toDate"></span></p>
  </body>
</html>

答案 1 :(得分:1)

如果你只想要普通的js解决方案w / out任何外部库。你可以试试这个。

var dateNow = new Date();
var firstDayOfTheWeek = (dateNow.getDate() - dateNow.getDay()) + 1; // Remove + 1 if sunday is first day of the week.
var lastDayOfTheWeek = firstDayOfTheWeek + 6;
var firstDayOfLastWeek = new Date(dateNow.setDate(firstDayOfTheWeek - 7));
var lastDayOfLastWeek = new Date(dateNow.setDate(lastDayOfTheWeek - 7));

在上面的解决方案中,firstDataOfLastWeek将是星期一的前一周,而lastDayOfLastWeek将是星期日的前一周。