Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
 }
like image 596
user2236497 Avatar asked Apr 03 '14 23:04

user2236497


3 Answers

Use Moment.js

daysAgo = {}
for(var i=1; i<=7; i++) {
  daysAgo[i] = moment().subtract(i, 'days').format("DD MM YYYY")
}
return daysAgo
like image 99
Ryan Bigg Avatar answered Oct 22 '22 23:10

Ryan Bigg


Or the ES6 way:

const dates = [...Array(7)].map((_, i) => {
    const d = new Date()
    d.setDate(d.getDate() - i)
    return d
})
like image 40
francis Avatar answered Oct 23 '22 01:10

francis


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

like image 31
adeneo Avatar answered Oct 22 '22 23:10

adeneo