Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last week date with jQuery/Javascript

Tags:

I'm trying to get the last week date in JavaScript, without the time.

So for example, 10-02-2012, instead of 10-02-12 13:34:56 GMT.

Is there an easy solution out there for this?

Thank you!

Edit:

I'm trying to make this dynamic, so that the resulting variable is always one week before the current date. Here's what I've done to calculate the today variable, if this helps or can be used!

var currentTime = new Date();
var month = currentTime.getMonth() + 1
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var today = month + "-" + day + "-" + year;
alert(today)
like image 917
streetlight Avatar asked Oct 09 '12 18:10

streetlight


People also ask

How to get the last week date in JavaScript?

To get last week's date, use the Date() constructor to create a new date, passing it the year, month and the day of the month - 7 to get the date of a week ago. Copied! function getLastWeeksDate() { const now = new Date(); return new Date(now. getFullYear(), now.

How to get one week date in JavaScript?

getDate() method. You can then go ahead and add 7 more days to increase the days by one week. Increase the days of a JavaScript date instance using the . setDate() method.

How to get week start and end date in js?

You can also use following lines of code to get first and last date of the week: var curr = new Date; var firstday = new Date(curr. setDate(curr. getDate() - curr.

How do I display current week in HTML?

HTML input type="week"


1 Answers

I prefer something like this ​

function getLastWeek() {
  var today = new Date();
  var lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
  return lastWeek;
}

var lastWeek = getLastWeek();
var lastWeekMonth = lastWeek.getMonth() + 1;
var lastWeekDay = lastWeek.getDate();
var lastWeekYear = lastWeek.getFullYear();

var lastWeekDisplay = lastWeekMonth + "/" + lastWeekDay + "/" + lastWeekYear;
var lastWeekDisplayPadded = ("00" + lastWeekMonth.toString()).slice(-2) + "/" + ("00" + lastWeekDay.toString()).slice(-2) + "/" + ("0000" + lastWeekYear.toString()).slice(-4);

console.log(lastWeekDisplay);
console.log(lastWeekDisplayPadded);

And if you're using jQuery UI, you can do this instead of the manual steps to build the string

var lastWeekDisplay = $.datepicker.formatDate('mm/dd/yy', getLastWeek());

Or for today

var todayDisplay = $.datepicker.formatDate('mm/dd/yy', new Date());
like image 193
CaffGeek Avatar answered Sep 21 '22 01:09

CaffGeek