Search code examples
javascriptdayjs

How to filter yesterday in the array of dates


How to filter yesterday in the array of dates. Right now, the output of the filter is the todays date. It should output the 2023-25-01

dayjs.extend(dayjs_plugin_isYesterday);

const arrOfDates = [ 1674670772417, 1674604800000, 1674518400000 ]
console.log( dayjs( arrOfDates[ 0 ] ).format( 'YYYY-DD-MM' ) ) // Should output 2023-26-01
console.log( dayjs( arrOfDates[ 1 ] ).format( 'YYYY-DD-MM' ) ) // Should output 2023-25-01
console.log( dayjs( arrOfDates[ 2 ] ).format( 'YYYY-DD-MM' ) ) // Should output 2023-24-01

arrOfDates.filter( date => {
    if ( dayjs( date ).add( -1, 'day' ).isYesterday() ) {
    console.log(dayjs(date).format('YYYY-DD-MM'), 'Result') // outputs 2023-26-01 which is incorrect. It should only output 2023-25-01
    }
} )
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.7/plugin/isYesterday.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>


Solution

  • No need for dayjs( date ).add( -1, 'day' ) while filtering. this updates the date value before checking isYesterday

    dayjs.extend(dayjs_plugin_isYesterday);
    
    const arrOfDates = [ 1674670772417, 1674604800000, 1674518400000 ]
    //const arrOfDates = [ dayjs().add(-1, 'day'), dayjs(), dayjs().add(1, 'day') ]
    console.log( dayjs( arrOfDates[ 0 ] ).format( 'YYYY-DD-MM' ) ) // Should output 2023-26-01
    console.log( dayjs( arrOfDates[ 1 ] ).format( 'YYYY-DD-MM' ) ) // Should output 2023-25-01
    console.log( dayjs( arrOfDates[ 2 ] ).format( 'YYYY-DD-MM' ) ) // Should output 2023-24-01
    
    arrOfDates.filter( date => {
    if ( dayjs( date ).isYesterday() ) {
    console.log(dayjs(date).format('YYYY-DD-MM'), 'Result') // outputs 2023-26-01 which is incorrect. It should only output 2023-25-01
    return true;
    }
    return false;
    } )
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.7/plugin/isYesterday.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>