How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

后端 未结 25 2039
遥遥无期
遥遥无期 2020-11-22 12:57

The question is how to format a JavaScript Date as a string stating the time elapsed similar to the way you see times displayed on Stack Overflow.

e.g.<

25条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 13:33

    Here's what I did (the object returns the unit of time along with its value):

    function timeSince(post_date, reference)
    {
    	var reference = reference ? new Date(reference) : new Date(),
    		diff = reference - new Date(post_date + ' GMT-0000'),
    		date = new Date(diff),
    		object = { unit: null, value: null };
    	
    	if (diff < 86400000)
    	{
    		var secs  = date.getSeconds(),
    			mins  = date.getMinutes(),
    			hours = date.getHours(),
    			array = [ ['second', secs], ['minute', mins], ['hour', hours] ];
    	}
    	else
    	{
    		var days   = date.getDate(),
    			weeks  = Math.floor(days / 7),
    			months = date.getMonth(),
    			years  = date.getFullYear() - 1970,
    			array  = [ ['day', days], ['week', weeks], ['month', months], ['year', years] ];
    	}
    
    	for (var i = 0; i < array.length; i++)
    	{
    		array[i][0] += array[i][1] != 1 ? 's' : '';
    
    		object.unit  = array[i][1] >= 1 ? array[i][0] : object.unit;
    		object.value = array[i][1] >= 1 ? array[i][1] : object.value;
    	}
    
    	return object;
    }

提交回复
热议问题