Javascript String toSeconds()

Description

Javascript String toSeconds()


String.prototype.toSeconds=function(){
  if(!/\d\d:[0-5][0-9]:[0-5][0-9]/.test(this)) return null;
  var arr=this.split(':');
  return arr[0]*3600+arr[1]*60+arr[2];
}
console.log('99:59:59'.toSeconds());

Javascript String toSeconds()

// http://www.codewars.com/kata/regexp-basics-parsing-time

String.prototype.toSeconds = function() {
  let m = this.valueOf().match(/^(\d{2}):([0-5]\d):([0-5]\d)$/);
  if (!m) return null;

  return +m[1] * 36e2 + +m[2] * 60 + +m[3];
}

Javascript String toSeconds()

//String Functions
String.prototype.toSeconds = function(){
 var data = this.split(':');
 
 if(data.length == 1){
  return parseFloat(data[0]);
 }
 else if(data.length == 2){
  return data[0] * 60 + parseFloat(data[1]);
 }
 else{//w w  w. j a va 2 s  . c  o  m
  throw new NumberFormatException("Invalid time format: \"" + this + "\", please validate your lyrics file.");
 }
};



PreviousNext

Related