Tuesday, July 17, 2012

Bytes to gigs, megs, kilos, and bytes

A units-to-readable conversion. My usage wraps this with a check for zero or null bytes and skips this function altogether.

function convertBytesGMKB(bytes){
 try{     
  var message = "";
  var gigs = Math.floor(bytes/Math.pow(1024,3));
  var divisorForMegs = bytes % Math.pow(1024,3);
  var megs = Math.floor(divisorForMegs / Math.pow(1024,2));
  var divisorForKilos = divisorForMegs % Math.pow(1024,2);
  var kilos = Math.floor(divisorForKilos / 1024);
  var divisorForBytes = divisorForKilos % 1024;
  var finalBytes = divisorForBytes;
  message = ((gigs > 0)?gigs+"g ":"")+((megs > 0)?megs+"m ":"")+((kilos > 0)?kilos+"k ":"")+finalBytes+"b";
  return message;
 }catch(e){
  console.log('convertBytesGMKB error: ', e);
 }
}

var content = convertBytesGMKB(Number(value));

Seconds to Weeks, Days, Hours, Minutes, Seconds

Seems converting to one unit is all over the interwebz. But, I couldn't find this so I posted my solution... This converts seconds to weeks, days, hours, minutes, seconds for readablity. In my usage it is wrapped in a check that skips it entirely if the seconds value is 0 or null.

function convertSecondsWDHMS(seconds){
 try{
  var message = "";
  var weeks = Math.floor(seconds/604800);
  var divisorForDays = seconds % 604800;
  var days = Math.floor(divisorForDays/86400);
  var divisorForHours = divisorForDays % 86400;
  var hours = Math.floor(divisorForHours / 3600);
  var divisorForMinutes = divisorForHours % 3600;
  var minutes = Math.floor(divisorForMinutes / 60);
  var divisorForSeconds = divisorForMinutes % 60;
  var finalSeconds = divisorForSeconds;
  message = ((weeks > 0)?weeks+"w ":"")+((days > 0)?days+"d ":"")+((hours > 0)?hours+"h ":"")+((minutes > 0)?minutes+"m ":"")+finalSeconds+"s";
  return message;
 }catch(e){
  console.log('convertSecondsWDHMS error: ', e);
 }
}

var content = convertSecondsWDHMS(Number(value));