javascript 获取过去 7 天日期的最有效方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22850929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:53:01  来源:igfitidea点击:

Most efficient way to get the dates for the past 7 days?

javascriptdatedays

提问by user2236497

I've got two functions which I can use to get the dates of the past 7 days and formats the into a particular format but it's pretty slow, does anybody know of a better way maybe using a loop or something similar?

我有两个函数可以用来获取过去 7 天的日期并将其格式化为特定格式,但速度很慢,有人知道使用循环或类似的更好的方法吗?

 function formatDate(date){

    var dd = date.getDate();
    var mm = date.getMonth()+1;
    var yyyy = date.getFullYear();
    if(dd<10) {dd='0'+dd}
    if(mm<10) {mm='0'+mm}
    date = mm+'/'+dd+'/'+yyyy;
    return date
 }

 function Last7Days () {

      var today = new Date();
      var oneDayAgo = new Date(today);
      var twoDaysAgo = new Date(today);
      var threeDaysAgo = new Date(today);
      var fourDaysAgo = new Date(today);
      var fiveDaysAgo = new Date(today);
      var sixDaysAgo = new Date(today);

      oneDayAgo.setDate(today.getDate() - 1);
      twoDaysAgo.setDate(today.getDate() - 2);
      threeDaysAgo.setDate(today.getDate() - 3);
      fourDaysAgo.setDate(today.getDate() - 4);
      fiveDaysAgo.setDate(today.getDate() - 5);
      sixDaysAgo.setDate(today.getDate() - 6);

      var result0 = formatDate(today);
      var result1 = formatDate(oneDayAgo);
      var result2 = formatDate(twoDaysAgo);
      var result3 = formatDate(threeDaysAgo);
      var result4 = formatDate(fourDaysAgo);
      var result5 = formatDate(fiveDaysAgo);
      var result6 = formatDate(sixDaysAgo);

      var result = result0+","+result1+","+result2+","+result3+","+result4+","+result5+","+result6;

      return(result);
 }

回答by adeneo

function Last7Days () {
    var result = [];
    for (var i=0; i<7; i++) {
        var d = new Date();
        d.setDate(d.getDate() - i);
        result.push( formatDate(d) )
    }

    return(result.join(','));
}

FIDDLE

小提琴

Or another solution for the whole thing

或者整个事情的另一个解决方案

function Last7Days () {
    return '0123456'.split('').map(function(n) {
        var d = new Date();
        d.setDate(d.getDate() - n);

        return (function(day, month, year) {
            return [day<10 ? '0'+day : day, month<10 ? '0'+month : month, year].join('/');
        })(d.getDate(), d.getMonth(), d.getFullYear());
    }).join(',');
 }

FIDDLE

小提琴

回答by Ryan Bigg

Use Moment.js

使用Moment.js

daysAgo = {}
for(var i=1; i<=7; i++) {
  daysAgo[i] = moment().subtract(i, 'days').format("DD MM YYYY")
}
return daysAgo

回答by zerkms

var dates = Array.apply(null, new Array(7))
     .map(function() {
         return new Date();
     })
     .map(function(v, i) {
         v.setDate(v.getDate() - i);
         return v;
     })
     .map(function(v) {
         return formatDate(v);
     })
     .reverse()
     .join(',');

JSFiddle: http://jsfiddle.net/R5dnu/1/

JSFiddle:http: //jsfiddle.net/R5dnu/1/

回答by Litterfeldt

I like as short and efficient code as possible, might not be the best but IMO best of both worlds:

我喜欢尽可能简短有效的代码,可能不是最好的,但 IMO 是两全其美的:

Array(7) // Create empty array of specified length, here a week.
    .fill(new Date()) // Fill it with dates of your choice, here today.
    .map((today, i) => today - 8.64e7 * i) // Subtract days worth of time times the index
    .map(day => formatDate(day)) // format your dates however you like

回答by carlitoxenlaweb

Based on @adeneo solution, i think we could send the number of days... Not the 7 days solution but this could be a better way:

基于@adeneo 解决方案,我认为我们可以发送天数......不是 7 天的解决方案,但这可能是一个更好的方法:

function LastDays (n, option) {
  let arr = Array.apply(0, Array(n)).map(function(v,i){return i}),
    weekday = new Array(7);
      
  weekday[0] = "Sunday";
  weekday[1] = "Monday";
  weekday[2] = "Tuesday";
  weekday[3] = "Wednesday";
  weekday[4] = "Thursday";
  weekday[5] = "Friday";
  weekday[6] = "Saturday";
  
  return arr.map(function(n) {
    let date = new Date();
    date.setDate(date.getDate() - n);
    return (function(day, month, year, weekendDay) {
     switch(option) {
       case 'weekday': return weekday[weekendDay];
       default: return [day<10 ? '0'+day : day, month<10 ? '0'+month : month, year].join('/');
      }
    })(date.getDate(), date.getMonth(), date.getFullYear(), date.getDay());
  }).join(', ');
}

document.getElementById("testA").innerHTML = LastDays(3)
document.getElementById("testB").innerHTML = LastDays(5,'weekday')
<div id="testA"></div>

<hr/>

<div id="testB"></div>

FIDDLE

小提琴

回答by RobG

Well, one more won't hurt. Note that dates in m/d/y format are pretty confusing to many.

嗯,再来一个不会痛的。请注意,m/d/y 格式的日期对许多人来说非常混乱。

// Get 7 days prior to provided date or today
function last7Days(d) {
  d = +(d || new Date()), days = [], i=7;
  while (i--) {
    days.push(formatUSDate(new Date(d-=8.64e7)));
  }
  return days;
}

// Return date string in mm/dd/y format
function formatUSDate(d) {
  function z(n){return (n<10?'0':'')+ +n;}
  return z(d.getMonth() + 1) + '/' + z(d.getDate()) + '/' + d.getFullYear();
}

console.log(last7Days().join('\n'));