e v e r n i t e February 2016

JavaScript \ Get Date of Last Thursday

How can i Get Date of Last Thursday via JavaScript?

If Thursday is today then get -7 days.

After that format output like '17 April 2016'.

Answers


gurvinder372 February 2016

var weekdays = [ "Sun", "Mon", "Tue", "Wed", "Thurs", "Fri", "Sat" ];

function getDateForLastOccurence( strDay )
{
   var date = new Date();
   var index = weekDays.indexOf(strDay);
   var difference =  date.getDay() - index; 
   if (difference < 0 ) 
   {
      difference = -7 - difference;
   }
   date.setDate( date.getDate() + difference );
   return  date;
}

getDateForLastOccurence( "Tue" );
getDateForLastOccurence( "Thurs" );


Yoplaboom February 2016

First it would be easier to help you by sharing your code ;)

You can get last Thursday by using the method Date.getDay()which returning the current day of the week.

Like this :

var now = new Date();
var daysAfterLastThursday = (-7 + 4) - now.getDay(); // 7 = number of days in week, 4 = the thursdayIndex (0= sunday)
var currentMs = now.getTime();
var lastThursday = new Date(currentMs + (daysAfterLastThursday * 24 * 60 * 60 * 1000));
alert("Last Thursday : " + lastThursday);

jsFiddle


Avinash February 2016

Simple, you can do it yourself.

  1. Find current day d
  2. Add d by 3
  3. Mod the result of step 2 by 7 using (result % 7)
  4. If result of step 3 is 0 subtract 7 from today's date, else subtract result of step 3 from today's date.

Post Status

Asked in February 2016
Viewed 2,246 times
Voted 7
Answered 3 times

Search




Leave an answer