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?
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With