Text Resizer Text Resizer
February 7th, 2012
You're browsing: Scriptmatico.Com » Javascript » Sumar Horas Con Javascript

Sumar Horas Con Javascript

Posted on mar 07 in Javascriptby PrintText Resizer Text Resizer

Esta funcion en javascript nos ayuda a sumarle cierto tiempo a una hora dada y con la ayuda de otras dos funciones le doy formato a la hora debido a que la funcion normalmente me retorna 8:3 en lugar de retornarme 08:03 bien pues con las funciones formatString y formatString2 le doy el formato deseado a la hora.

La funcion tiene tres parametros el val1 que es la hora que le enviemos la variable txtBox que es el elemento en el cual devolveremos el valor y el tiempo que es lo que le sumaremos a la hora que le enviamos.

Bien no creo que sea muy complicado que lo implementen. Pueden copiar y hacer con el codigo lo que gusten solo les pido que si lo cuelgan en su web pongan un link de referencia hacia este post.

Aqui les pongo el codigo.

JavaScript:
  1. function sumaTiempos(val1, txtBox,tiempo){
  2.  
  3.     devol=document.getElementById(txtBox);
  4.     t1=val1;
  5.     t2=tiempo;
  6.  
  7.     var dot1 = t1.indexOf(":");
  8.     var dot2 = t2.indexOf(":");
  9.     var m1 = t1.substr(0, dot1);
  10.     var m2 = t2.substr(0, dot2);
  11.     var s1 = t1.substr(dot1 + 1);
  12.     var s2 = t2.substr(dot2 + 1);
  13.     var sRes = (Number(s1) + Number(s2));
  14.     var mRes;
  15.     var addMinute = false;
  16.     if (sRes>= 60){
  17.         addMinute = true;
  18.         sRes -= 60;
  19.     }
  20.     mRes = (Number(m1) + Number(m2) + (addMinute? 1: 0));
  21.  
  22.     devol.value= formatString2(String(mRes),2) + ":" + formatString(String(sRes),2);
  23.  
  24. }
  25.  
  26. function formatString2(string, len)
  27. {
  28.  
  29.     if (string.length <len)
  30.     {
  31.         addchar=(len - string.length) ;
  32.         for (i = 0; i <addchar; i++)
  33.         {
  34.  
  35.             string="0"+string ;
  36.         }
  37.     }
  38.  
  39.     if (string.length> len)
  40.     {
  41.         string=substr(string,0,len);
  42.     }
  43.  
  44.     return string;
  45.  
  46. }
  47.  
  48. function formatString(string, len)
  49. {
  50.  
  51.     if (string.length <len)
  52.     {
  53.         addchar=(len - string.length) ;
  54.         for (i = 0; i <addchar; i++)
  55.         {
  56.  
  57.             string=string +"0";
  58.         }
  59.     }
  60.  
  61.     if (string.length> len)
  62.     {
  63.         string=substr(string,0,len);
  64.     }
  65.  
  66.     return string;
  67.  
  68. }

Related posts:

  1. Sumar horas con php
  2. Javascript scrollAmount en Safari no trabaja correctamente.
  3. Argumentos opcionales en C# ??
  4. Crear archivos ZIP con PHP (Otra forma)

Leave a Reply

You must be logged in to post a comment.

Back to Top