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);
}
JSFiddle: http://jsfiddle.net/R5dnu/1/
I like as short and efficient code as possible, might not be the best but IMO best of both worlds:
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:
FIDDLE
Well, one more won't hurt. Note that dates in m/d/y format are pretty confusing to many.
FIDDLE
Or another solution for the whole thing
FIDDLE
Use Moment.js