JavaScript - restar fechas

 
Vista:
sin imagen de perfil

restar fechas

Publicado por movick (90 intervenciones) el 30/09/2014 03:19:54
quiero aplicar este codigo para calcular la edad:

1
2
3
4
5
6
7
8
9
10
function restaFechas (f1,f2)
 {
 var aFecha1 = f1.split('/');
 var aFecha2 = f2.split('/');
 var fFecha1 = Date.UTC(aFecha1[2],aFecha1[1]-1,aFecha1[0]);
 var fFecha2 = Date.UTC(aFecha2[2],aFecha2[1]-1,aFecha2[0]);
 var dif = fFecha2 - fFecha1;
 var dias = Math.floor(dif / (1000 * 60 * 60 * 24));
 return dias;
 }

y la idea es aplicarlo a esta linea:
1
2
3
4
<TR>
	<td>Fecha de Nac.:</td>
    <td><input type="text" size=10 maxlength=10 name="fechanac" onKeyUp="mascara(this,'-',patron,true)"></td>
</TR>
la idea es que cuando escriba la fecha calcule la edad, ¿pero como hago para que al escribir la fecha el name reste de acuerdo a la funcion y de como resultado la edad?
Por supuesto el objetivo es utilizar el onBlur().
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de xve
Val: 3.162
Oro
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

restar fechas

Publicado por xve (2100 intervenciones) el 30/09/2014 08:57:58
Hola Movick, no entiendo muy bien tu código...

En el formulario llamas a la función mascara, que no la muestras...
La función que muestras, parece que únicamente devuelve los días entre dos fechas.

En esta misma página, existen códigos que te pueden servir:
http://www.lawebdelprogramador.com/codigo/JavaScript/2380-Calcular_la_edad_desde_una_fecha_dada_en_HTML5.html
http://www.lawebdelprogramador.com/codigo/JavaScript/1143-Calculo_de_la_edad.html

Si nos puedes comentar...
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

restar fechas

Publicado por movick (90 intervenciones) el 30/09/2014 14:00:28
Que tal Xve. bueno el asunto es que el codigo es bastante largo pero es este:
Nota: esta en negritas la funcion mascara y la otra porcion a donde se debe aplicar, el asunto alli es: Como aplicaria esa funcion a al <td> o debo crear otra funcion en javascript y como?.
Estuve analizando los codigos que me enviaste, y estan buenas pero en una de ellas el año posee dos digitos.
Ayudame por favor.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
<?php
   $connect = pg_connect("host=localhost port=5432 dbname=pediatria user=postgres password=Wraip");
   $vacunas = "SELECT * FROM vacunas ORDER BY descripcion";
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
      <script language="JavaScript" src="calendario.js"></script>
      <script language="JavaScript" src="overlib_mini.js"></script>
<SCRIPT type="text/javascript">
var patron = new Array(2,2,4)
var patron2 = new Array(1,3,3,3,3)
function mascara(d,sep,patron,nums){
if(d.valant != d.value){
	val = d.value
	largo = val.length
	val = val.split(sep)
	val2 = ''
	for(r=0;r<val.length;r++){
		val2 += val[r]
	}
	if(nums){
		for(z=0;z<val2.length;z++){
		  if(isNaN(val2.charAt(z))){
			letra = new RegExp(val2.charAt(z),"g")
			val2 = val2.replace(letra,"")
		   }
		}
	}
	val = ''
	val3 = new Array()
	for(s=0; s<patron.length; s++){
		val3[s] = val2.substring(0,patron[s])
		val2 = val2.substr(patron[s])
	}
	for(q=0;q<val3.length; q++){
		if(q ==0){
			val = val3[q]
		}
		else{
			if(val3[q] != ""){
				val += sep + val3[q]
			}
		}
	}
	d.value = val
	d.valant = val
	}
}
 
 
/***/
function validatePass(campo) {
    var RegExPattern = /(^[0-9]+.[0-9]+$)/;
    var errorMessage = 'Debe Escribir el Peso con un punto y decimales';
    if ((campo.value.match(RegExPattern)) && (campo.value!='')) {
    } else {
        alert(errorMessage);
        campo.focus();
    }
}
 
function validateTalla(talla) {
    var RegExPattern = /(^[0-9]+.[0-9]+$)/;
    var errorMessage = 'Debe Escribir la Talla con un punto y decimales';
    if ((talla.value.match(RegExPattern)) && (talla.value!='')) {
    } else {
        alert(errorMessage);
        talla.focus();
    }
}
 
function validateCircEncef(circenc) {
    var RegExPattern = /(^[0-9]+.[0-9]+$)/;
    var errorMessage = 'Debe Escribir el Perimetro Craneal con un punto y decimales';
    if ((circenc.value.match(RegExPattern)) && (circenc.value!='')) {
    } else {
        alert(errorMessage);
        circenc.focus();
    }
}
 
function validateCircBrazo(circbra) {
    var RegExPattern = /(^[0-9]+.[0-9]+$)/;
    var errorMessage = 'Debe Escribir la Circunferencia del Brazo con un punto y decimales';
    if ((circbra.value.match(RegExPattern)) && (circbra.value!='')) {
    } else {
        alert(errorMessage);
        circbra.focus();
    }
}
 
 
</script>
<title>Pacientes</title>
</head>
 
<body>
<div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div>
<form action="cargapacientes.php" method="POST" name="form1">
<!--<fieldset style='width:auto'><LEGEND>Ingreso Paciente</LEGEND> 
-->
<?php
$connect = pg_connect("host=localhost port=5432 dbname=pediatria user=postgres password=1234");
?>
   <table>
      <tr>
	    <td >Nro de Historia:</td>
<?php
$hoy=date('d-m-Y');
 
 
$query= pg_query("SELECT max(nrohistoria)+1 as MaxNroHistoria FROM paciente");
 if ($row = pg_fetch_row($query))
 {
  $id = str_pad(trim($row[0]),4,"0",STR_PAD_LEFT);
 }
?>
<td class='sr'><input type='text' readonly="T" value="<?php echo $id; ?>" name='nrohistoria' size='10' maxlength='10' align='right'/></td></tr>
	  <tr>
		<td class="sr" align='right' style="text-decoration:none">Nombres:</td>
		<td class="sr"><input type="text" name="nombres" size="50" maxlength="50" align="right"/></td>
	  </tr>
 
	  <tr>
		<td class="sr" align='right' style="text-decoration:none">Apellidos:</td>
		<td class="sr"><input type="text" name="apellidos" size="50" maxlength="50" align="right"/></td>
	  </tr>
 
	  <tr>
		<td class="sr" align='right' style="text-decoration:none">Direccion:</td>
		<td class="sr"><input type="text" name="direccion" size="120" maxlength="120" align="right"/>
		</td>
	  </tr>
	  <tr>
		<td class="sr" align='right' style="text-decoration:none">Telefono:</td>
		<td class="sr"><input type="text" name="telefono" size="10" maxlength="10" align="right"/>
		</td>
	  </tr>
<TR>
	<td>Fecha de Nac.:</td>
    <td><input type="text" size=10 maxlength=10 name="fechanac" onKeyUp="mascara(this,'-',patron,true)">
<?php
     $anio = $_POST['fechanac'];
$date2 = date('d-m-Y');//la fecha del computador
echo "</br>";
 
$diff = abs(strtotime($date2) - strtotime($anio));
echo "</br> Años";
$years = floor($diff / (365*60*60*24));
echo "</br> Meses";
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
echo "</br> Dias";
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
    echo "</br>";
?>
</td>
</TR>
<tr>
     <td align='right'>Sexo:</td>
     <td><select name="cmbosexo"><option value="0">[Seleccione el Sexo]</option>
 
<?php
   $sexos = "SELECT * FROM sexo";
 
//*** crear la tabla sexo
$sexo = @pg_query($connect,$sexos);
while($selectsex = @pg_fetch_array($sexo))
          {
			$codigo = $selectsex['codigo'];
            $descripsex = $selectsex['descripcion'];
            echo "<OPTION VALUE='$codigo'>$descripsex</OPTION>";
          }
 
?>
        </select></td></tr>
 
<tr>
     <td align='right'>Grupo Sanguineo:</td>
     <td><select name="cmbosang"><option value="0">[Seleccione el Grupo Sanguineo]</option>
<?php
$gsang = "SELECT * FROM gsanguineo ORDER BY descripcion";
$gsang = @pg_query($connect,$gsang);
while($selectgsang = @pg_fetch_array($gsang))
          {
			$codigo = $selectgsang['codigo'];
            $descrip = $selectgsang['descripcion'];
            echo "<OPTION VALUE='$codigo'>$descrip</OPTION>";
          }
 
?>
        </select></td></tr>
<!---->
<tr>
     <td align='right' class='sr' >Hcm:</td>
     <td><select name="cmbotipgasto"><option value="0">[Seleccione una Clinica]</option>
<?php
$tipo_gasto = "SELECT * FROM hcm ORDER BY descripcion";
$tipo_gasto = @pg_query($connect,$tipo_gasto);
while($select3 = @pg_fetch_array($tipo_gasto))
		  {
			$cCodigo = $select3['codigo'];
            $descrip = $select3['descripcion'];
            echo "<OPTION VALUE='$cCodigo'>$descrip</OPTION>";
          }
?>
        </select></td></tr>
<!---->
 
</table>
</fieldset>
<table><tr><td><hr width="900" align="center"></td></tr></table>
<table align='center' border='1' bordercolor='#00CC99' bgcolor='#99CC00'>
  <tr>
	              <th>Fecha:
		     	       <td><input type='text' value=<?php echo $hoy?> name='fecha' readonly='.F.'></td></tr>
  <tr>
 
           <th width='100' style='font-size:15px;'>Peso:
		               <td><input type='text' name='peso' onBlur="validatePass(this);"></td></tr>
  <tr>
           <th width='100' style='font-size:15px;'>Talla:
		     	       <td><input type='text' name='talla' onBlur="validateTalla(this);"></td></tr>
  <tr>
           <th width='100' style='font-size:15px;'>Circ Encef:
		     	       <td><input type='text' name='circenf' onBlur="validateCircEncef(this);"></td></tr>
  <tr>
           <th width='100' style='font-size:15px;'>Circ Brazo:
		     	       <td><input type='text' name='circbrazo' onBlur="validateCircBrazo(this);"></td></tr>
<?php
/*$SqlCommand="update MiTabla set HepatitisA='$HepatitisA',HepatitisB='$HepatitisB'
where IdPaciente='$IdPaciente' ";*/
?>
  <tr>
           <th width='100' style='font-size:15px;'>
   		   Hepatitis A:<td>
		   <input name="checkhepa" type="checkbox" value="Hepa">
           Polio:
		   <input name="checkpoli" type="checkbox" value="Poli">
           Fiebre Amarilla:
		   <input name="checkfieama" type="checkbox" value="">
    	   Difteria-Tetanos:
		   <input name="difteriateta" type="checkbox" value="">
		   Varicela:
		   <input name="varicela" type="checkbox" value="">
		   Meningitis Meningococia:
		   <input name="meningitis" type="checkbox" value="">
		</td>
 
  <tr>
           <th width='100' style='font-size:15px;'>
		   Hepatitis B:<td>
		   <input name="checkhepb" type="checkbox" value="Hepab">
		   Haemophilus Influenza:
		   <input name="checkinfluenzae" type="checkbox" value="">
		   Sarampion Rubeola Parotiditis:
		   <input name="checksaramp" type="checkbox" value="">
		   Vph:
		   <input name="checkvph" type="checkbox" value="">
		   Rotavirus:
		   <input name="checkrotavirus" type="checkbox" value="">
		   Tuberculosis:
		   <input name="checktuberculosis" type="checkbox" value="">
  	    </td>
  </tr>
  <tr>
           <th width='100' style='font-size:15px;'>Consulta:
		     	       <td><textarea name='consulta' cols='70' rows='5'></textarea></td></tr>
 
	   </table>
 
<table align="center">
   <tr>
    <td>
         <input class="color1" type="submit" name="action" value="Guardar"/>
         <input class="color1" type="reset" value="Deshacer">
    </td>
    </tr>
</table>
 
</form>
</body>
 
</html>
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar