Pregunta

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?

 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);
 }
¿Fue útil?

Solución

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

Otros consejos

Or the ES6 way:

const dates = [...Array(7)].map((_, i) => {
    const d = new Date()
    d.setDate(d.getDate() - i)
    return d
})

Use Moment.js

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

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

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
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/

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

// 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'));

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:

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

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());
var Today = moment(new Date()).format('DD-MM-YYYY');
var yesterdaydate = moment(new Date((new Date()).valueOf() - 1000 * 60 * 60 * 24)).format('DD-MM-YYYY');
var thirdDate = moment(new Date((new Date()).valueOf() - 1000 * 60 * 60 * 24 * 2)).format('DD-MM-YYYY');
var Fourthdate = moment(new Date((new Date()).valueOf() - 1000 * 60 * 60 * 24 * 3)).format('DD-MM-YYYY');
var fifthdate = moment(new Date((new Date()).valueOf() - 1000 * 60 * 60 * 24 * 4)).format('DD-MM-YYYY');
var Sixthdate = moment(new Date((new Date()).valueOf() - 1000 * 60 * 60 * 24 * 5)).format('DD-MM-YYYY');
var sevendate = moment(new Date((new Date()).valueOf() - 1000 * 60 * 60 * 24 * 6)).format('DD-MM-YYYY');
var eightdate = moment(new Date((new Date()).valueOf() - 1000 * 60 * 60 * 24 * 7)).format('DD-MM-YYYY');
let lastsevenDays = Today + yesterdaydate + thirdDate + Fourthdate + fifthdate + Sixthdate + sevendate + eightdate;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top