All files / utils dateUtils.js

100% Statements 26/26
100% Branches 16/16
100% Functions 3/3
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45  13x   6x 4x 4x     6x 6x 6x 6x     18x 1x     17x 17x 17x   17x 1x     16x 1x 1x     15x 2x 2x     13x 12x 12x     1x      
 
const padWithZero = (n) => { return n < 10 ? '0' + n : n; }
 
const timestampToDate = (timestamp) => {
    var date = new Date(timestamp);
    return (date.getFullYear() + "-" + (padWithZero(date.getMonth()+1)) + "-" + padWithZero(date.getDate()));
}
 
const minutesInSeconds = 60;
const hourInSeconds = 60 * minutesInSeconds;
const dayInSeconds = 24 * hourInSeconds;
const weekInSeconds = 7 * dayInSeconds;
 
export function formatTime(timeString) {
    if (!timeString) {
        return "";
    }
 
    const now = new Date();
    const dateFromEpoch = new Date(timeString);
    const secondsPast = Math.floor((now - dateFromEpoch) / 1000);
 
    if (secondsPast < minutesInSeconds * 2) {
        return 'Online now';
    }
 
    if (secondsPast < hourInSeconds) {
        const minutes = Math.floor(secondsPast / 60);
        return `${minutes} minutes ago`;
    }
 
    if (secondsPast < dayInSeconds) {
        const hours = Math.floor(secondsPast / 3600);
        return `${hours} hour${hours > 1 ? 's' : ''} ago`;
    }
    
    if (secondsPast < weekInSeconds) {
        const days = Math.floor(secondsPast / 86400);
        return `${days} day${days > 1 ? 's' : ''} ago`;
    }
 
    return dateFromEpoch.toLocaleDateString();
}
 
export {timestampToDate, padWithZero};