Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript prototype function: decimal time value to a time string

On a project I'm currently working on in JavaScript, I'm using decimal formats so it's easier to calculate with rather than using an hour/minute format in strings (calendar related project). To display the time on the user's screen though, the timecode has to be shown as hh:mm.

I thought it would be great to use a String prototype function for this as it would allow me to use code like:

var time = 8.75;
document.write("Meeting at "+time.toTime()); // writes: Meeting at 8:45

So far, I've got that almost working, using:

String.prototype.toTime = function(){
    var hrs = this.toString().slice(0,this.indexOf("."));
    var min = Math.round(this.toString().slice(this.indexOf("."))/100*60);
    min = min<10 ? "0"+min : min.toString();
    return hrs+":"+min;
}

The problem, though, is that this will only work if the variable time is a string. Otherwise it will give an undefined error.

Would there be any way of applying the prototype to a different object in JavaScript, so that I don't have to use time.toString().toTime()?

Thanks!

like image 836
Oscar Avatar asked Oct 05 '22 23:10

Oscar


1 Answers

Firstly, you can add to the Number prototype. Many people will warn against modifying prototypes, which in many cases is justified. If there is a chance 3rd party scripts will be running alongside yours, it is a danger to modify prototypes.

Secondly, I simplified your code a little, using modulus, and floor to calculate the hrs and mins...

Number.prototype.toTime = function(){
  var hrs = Math.floor(this)
  var min = Math.round(this%1*60)
  min = min<10 ? "0"+min : min.toString();
  return hrs+":"+min;
}

var time = 8.25;
console.log("Meeting at "+time.toTime());
like image 188
Billy Moon Avatar answered Oct 10 '22 02:10

Billy Moon