Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get last week date starting monday to sunday in javascript

I want a javascript function that gives me start_date as the last week monday date and end_date as last week sunday date. So for example, today is 03/09/2016, so I want start_date = 02/29/2016 end_date = 03/06/2016

so far I have wriiten the code as

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

but its giving me date as

    03/07/2016 and 03/13/2016

how do I fix this to get the dates I want?

like image 292
Krystal Avatar asked Oct 25 '25 07:10

Krystal


2 Answers

If in case you just want plain js solution w/out any external libraries. You can try this instead.

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

In the above solution, firstDataOfLastWeek will be previous week Monday, and lastDayOfLastWeek will be previous week Sunday.

like image 144
Bretch Guire Garcinez Avatar answered Oct 27 '25 21:10

Bretch Guire Garcinez


If you have a lot of date handling to do, I can only strongly suggest that you use the moment.js library.

In this case, the dates would be :

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

Here you can see it in action :

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>
like image 43
Aaron Avatar answered Oct 27 '25 21:10

Aaron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!