简体   繁体   English

JavaScript \\ 获取上周四的日期

[英]JavaScript \ Get Date of Last Thursday

How can i Get Date of Last Thursday via JavaScript?如何通过 JavaScript 获取上周四的日期?

If Thursday is today then get -7 days.如果今天是星期四,那么得到 -7 天。

After that format output like '17 April 2016'.在该格式输出之后,如“2016 年 4 月 17 日”。

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.您可以使用Date.getDay()方法获取上周四,该方法返回一周中的当前日期。

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 js小提琴

Here's a function I wrote that works for all cases.这是我编写的适用于所有情况的函数。

/**
 * @param {Date} date - the initial Date
 * @param {('Mon'|'Tue'|'Wed'|'Thurs'|'Fri'|'Sat'|'Sun')} day - the day of week
 * @returns {Date} - the Date of last occurrence or same Date if day param is invalid
 */
function getLastDayOccurence (date, day) {
  const d = new Date(date.getTime());
  const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat'];
  if (days.includes(day)) {
    const modifier = (d.getDay() + days.length - days.indexOf(day)) % 7 || 7;
    d.setDate(d.getDate() - modifier);
  }
  return d;
}

If looking for the last occurrence of a Thursday from today, usage would be as follows:如果查找从今天起最后一次出现的星期四,则用法如下:

const lastThursday = getLastDayOccurence(new Date(), 'Thurs');

Also answered here: https://stackoverflow.com/a/59145062/5436697也在这里回答: https : //stackoverflow.com/a/59145062/5436697

Simple, you can do it yourself.很简单,你可以自己做。

  1. Find current day d查找当前日期 d
  2. Add d by 3将 d 加 3
  3. Mod the result of step 2 by 7 using (result % 7)使用 (result % 7) 将步骤 2 的结果修改为 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.如果第 3 步的结果是 0 从今天的日期减去 7,否则从今天的日期减去第 3 步的结果。

这可能是不好的形式,但我已经使用 PHP 的 strtotime 函数来做到这一点。

const d = "<?php echo date("d M Y", strtotime ("last thursday")); ?>";
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" );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM