获取过去7天日期的最有效方法是什么?

时间:2014-04-03 23:34:33

标签: javascript date days

我有两个函数可以用来获取过去7天的日期并将其格式化为特定的格式,但它很慢,有没有人知道更好的方法可能使用循环或类似的东西?< / p>

 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);
 }

8 个答案:

答案 0 :(得分:12)

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

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

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

答案 1 :(得分:3)

使用Moment.js

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

答案 2 :(得分:3)

ES6 方式:

anotherComponent

答案 3 :(得分:1)

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/

答案 4 :(得分:0)

嗯,还有一个不会受伤。请注意,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'));

答案 5 :(得分:0)

我喜欢尽可能短而高效的代码,可能不是两个方面都最好,但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

答案 6 :(得分:0)

基于@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

答案 7 :(得分:0)

function last7Days() {
      let today = new Date();
      let lastSevenDays = [today.toLocaleDateString()];
      let dateOffset;
      for (let i = 1; i < 7; i++) {
        dateOffset = (24 * 60 * 60 * 1000) //Reset the value evry iteration
        dateOffset *= i;
        today = new Date(); //Reset the day value evry iteration
        today.setTime(today.getTime() - dateOffset);
        lastSevenDays.push(today.toLocaleDateString());
      }
      return lastSevenDays;
    }
    console.log(last7Days());