- Timestamp:
- Mar 7, 2019 9:07:15 PM (5 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/js/Utilities.js
r654 r671 165 165 Uppercase the first letter of string. 166 166 --------------------------------------------------------------------- 167 > 'hello world'. trim()167 > 'hello world'.ucfirst() 168 168 Hello world 169 169 --------------------------------------------------------------------- … … 178 178 } 179 179 180 181 /* 182 Returns a human readable amount of time for the given amount of seconds. 183 Months are calculated using the real number of days in a year: 365.2422 / 12. 184 @param int seconds Seconds of time. 185 @param string max_unit Key value from the units array. 186 @return string Value of units elapsed. 187 --------------------------------------------------------------------- 188 > Strangecode.humanTime(3600) 189 1 hour 190 --------------------------------------------------------------------- 191 * @access public 192 * @version 1.0 193 * @since 06 Mar 2019 194 */ 195 Strangecode.humanTime = function(seconds, max_unit) { 196 // Units: array of seconds in the unit, singular and plural unit names. 197 var units = { 198 'second': [1, 'second', 'seconds'], 199 'minute': [60, 'minute', 'minutes'], 200 'hour': [3600, 'hour', 'hours'], 201 'day': [86400, 'day', 'days'], 202 'week': [604800, 'week', 'weeks'], 203 'month': [2629743.84, 'month', 'months'], 204 'year': [31556926.08, 'year', 'years'], 205 'decade': [315569260.8, 'decade', 'decades'], 206 'century': [3155692608, 'century', 'centuries'], 207 }; 208 209 // Max unit to calculate. 210 max_unit = typeof max_unit === 'string' && units[max_unit] ? max_unit : 'year'; 211 212 var final_time = seconds; 213 var final_unit = 'second'; 214 for (var k in units) { 215 if (seconds >= units[k][0]) { 216 final_time = seconds / units[k][0]; 217 final_unit = k; 218 } 219 if (max_unit == final_unit) { 220 break; 221 } 222 } 223 final_time = Number(final_time).toFixed(0); 224 return '{1} {2}'.format(final_time, (1 == final_time ? units[final_unit][1] : units[final_unit][2])); 225 } 226
Note: See TracChangeset
for help on using the changeset viewer.