In my JS project, I am using datatable plugin to show data where I have a date column which users can filter/search.
In order to help users to search using a logical string such as today
, thismonth
, lastweek
I am writting a fucntion which uses MomentJs.
I am looking at the most efficient way of writing this fuzzyDate
function.
function fuzzyDate(mydate){
var fuzzy1 = ''; var fuzzy2 = ''; var fuzzy3 = '';
var todaydt = moment(moment().format('YYYY-MM-DD'));
var daydiff = mydate.diff(todaydt,'day');
if (daydiff==-1){fuzzy1='Yesterday'}
if (daydiff==0){fuzzy1='Today'}
if (daydiff==1){fuzzy1='Tomorrow'}
var weekdiff = mydate.diff(todaydt,'week');
if (weekdiff==-1){fuzzy2='LastWeek'}
if (weekdiff==0){fuzzy2='ThisWeek'}
if (weekdiff==1){fuzzy2='NextWeek'}
var monthdiff = mydate.diff(todaydt,'month');
if (monthdiff==-1){fuzzy3='LastMonth'}
if (monthdiff==0){fuzzy3='ThisMonth'}
if (monthdiff==1){fuzzy3='NextMonth'}
return fuzzy1 + ' ' + fuzzy2 + ' ' + fuzzy3;
}
console.log( '2018-06-01 - ', fuzzyDate(moment('2018-06-01','YYYY-MM-DD')) ) ;
console.log( '2018-07-01 - ', fuzzyDate(moment('2018-07-01','YYYY-MM-DD')) ) ;
console.log( '2018-07-07 - ', fuzzyDate(moment('2018-07-07','YYYY-MM-DD')) ) ;
console.log( '2018-07-10 - ', fuzzyDate(moment('2018-07-10','YYYY-MM-DD')) ) ;
console.log( '2018-07-11 - ', fuzzyDate(moment('2018-07-11','YYYY-MM-DD')) ) ;
console.log( '2018-07-12 - ', fuzzyDate(moment('2018-07-12','YYYY-MM-DD')) ) ;
console.log( '2018-07-13 - ', fuzzyDate(moment('2018-07-13','YYYY-MM-DD')) ) ;
console.log( '2018-07-15 - ', fuzzyDate(moment('2018-07-15','YYYY-MM-DD')) ) ;
console.log( '2018-07-30 - ', fuzzyDate(moment('2018-07-30','YYYY-MM-DD')) ) ;
console.log( '2018-08-30 - ', fuzzyDate(moment('2018-08-30','YYYY-MM-DD')) ) ;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Output of the above function
2018-06-01 - LastMonth
2018-07-01 - LastWeek ThisMonth
2018-07-07 - ThisWeek ThisMonth
2018-07-10 - ThisWeek ThisMonth
2018-07-11 - Yesterday ThisWeek ThisMonth
2018-07-12 - Today ThisWeek ThisMonth
2018-07-13 - Tomorrow ThisWeek ThisMonth
2018-07-15 - ThisWeek ThisMonth
2018-07-30 - ThisMonth
2018-08-30 - NextMonth
fuzzyDate
toDate.prototype
. Makes nicely integrated, functionalDate
objects customize to your needs. To limit scope you can:var fuzzy = new Date()
then addfuzzyDate
tofuzzy.prototye
\$\endgroup\$