UNPKG

node-dateformatter

Version:

It formats a javascript date object

45 lines (40 loc) 1.84 kB
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ function format(units, timeunit){ return units === 1 ? units + ' ' + timeunit + ' ago' : units + ' ' + timeunit + 's ago'; } module.exports = function formatTime(dateCreated) { let diff = Math.abs(new Date() - Date.parse(dateCreated)); if (diff < (1000 * 60)) { // less than a minute let a = Math.floor(Math.abs(new Date() - Date.parse(dateCreated)) / (1000)); return format(a, 'second'); } else if (diff < (1000 * 60 * 60)) { // more than a minute and less than 60 minutes let a = Math.floor(Math.abs(new Date() - Date.parse(dateCreated)) / (1000 * 60)); return format(a, 'minute'); } else if (diff < (1000 * 60 * 60 * 24)) { // more than 60 minutes and less than 24 hours let a = Math.floor(Math.abs(new Date() - Date.parse(dateCreated)) / (1000 * 60 * 60)); return format(a, 'hour'); } else if (diff < (1000 * 60 * 60 * 24 * 7)) { // more than 24 hours and less than 7 days let a = Math.floor(Math.abs(new Date() - Date.parse(dateCreated)) / (1000 * 60 * 60 * 24)); return format(a, 'day'); } else if (diff < (1000 * 60 * 60 * 24 * 7 * 4.285)) { // more than 7 days and less than 4 weeks let a = Math.floor(Math.abs(new Date() - Date.parse(dateCreated)) / (1000 * 60 * 60 * 24 * 7)); return format(a, 'week'); } else if (diff < (1000 * 60 * 60 * 24 * 365)) { // more than 4.285 weeks and less than 365 days let a = Math.floor(Math.abs(new Date() - Date.parse(dateCreated)) / (1000 * 60 * 60 * 24 * 30)); return format(a, 'month'); } else { // more than a year let a = Math.floor(Math.abs(new Date() - Date.parse(dateCreated)) / (1000 * 60 * 60 * 24 * 365)); return format(a, 'year'); } }