Código de JavaScript - Obtener la diferencia en días entre dos fechas

Versión 1
estrellaestrellaestrellaestrellaestrella(7)

Publicado el 16 de Julio del 2014gráfica de visualizaciones de la versión: Versión 1
39.965 visualizaciones desde el 16 de Julio del 2014
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

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
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
 
    <script>
    /**
	 * Documentado en http://lwp-l.com/s2379
	 */
	function isValidDate(day,month,year)
	{
		var dteDate;
		month=month-1;
		dteDate=new Date(year,month,day);
		return ((day==dteDate.getDate()) && (month==dteDate.getMonth()) && (year==dteDate.getFullYear()));
	}
 
	/**
	 * Funcion para validar una fecha
	 * Tiene que recibir:
	 *  La fecha en formato español dd/mm/yyyy
	 * Devuelve:
	 *  true o false
	 */
	function validate_fecha(fecha)
	{
		var patron=new RegExp("^([0-9]{1,2})([/])([0-9]{1,2})([/])(19|20)+([0-9]{2})$");
 
		if(fecha.search(patron)==0)
		{
			var values=fecha.split("/");
			if(isValidDate(values[0],values[1],values[2]))
			{
				return true;
			}
		}
		return false;
	}
 
    function calcularDias()
    {
		var fechaInicial=document.getElementById("fechaInicial").value;
		var fechaFinal=document.getElementById("fechaFinal").value;
		var resultado="";
		if(validate_fecha(fechaInicial) && validate_fecha(fechaFinal))
		{
			inicial=fechaInicial.split("/");
			final=fechaFinal.split("/");
			// obtenemos las fechas en milisegundos
			var dateStart=new Date(inicial[2],(inicial[1]-1),inicial[0]);
            var dateEnd=new Date(final[2],(final[1]-1),final[0]);
            if(dateStart<dateEnd)
            {
				// la diferencia entre las dos fechas, la dividimos entre 86400 segundos
				// que tiene un dia, y posteriormente entre 1000 ya que estamos
				// trabajando con milisegundos.
				resultado="La diferencia es de "+(((dateEnd-dateStart)/86400)/1000)+" días";
			}else{
				resultado="La fecha inicial es posterior a la fecha final";
			}
		}else{
			if(!validate_fecha(fechaInicial))
				resultado="La fecha inicial es incorrecta";
			if(!validate_fecha(fechaFinal))
				resultado="La fecha final es incorrecta";
		}
		document.getElementById("resultado").innerHTML=resultado;
    }
    </script>
 
</head>
 
<body>
 
<form>
	<p>Introduce la fecha inicial y final en formato español dd/mm/yyyy</p>
	<input type="text" name="fechaInicial" id="fechaInicial" value="16/07/2014">
	<input type="text" name="fechaFinal" id="fechaFinal" value="17/07/2014">
 
	<input type="button" value="Calcular dias" onclick="calcularDias();">
</form>
<div id="resultado"></div>
 
</body>
</html>



Comentarios sobre la versión: Versión 1 (7)

Luis
21 de Enero del 2015
estrellaestrellaestrellaestrellaestrella
que tal bro una pregunta puedes ayudarme con el codigo pero en vez de poner yo la fecha la seleciones de un calendario men ...... claro si se puede gracias de antemano
Responder
Anonimo
1 de Octubre del 2016
estrellaestrellaestrellaestrellaestrella
solo necesitas eso o hay otra cosa????? (sarcasmo) jajajaj
Responder
Luis
4 de Octubre del 2016
estrellaestrellaestrellaestrellaestrella
Lamento haberte molestado bro
Responder
23 de Marzo del 2017
estrellaestrellaestrellaestrellaestrella
Saludos y si quiero que el formato sea YYYY-MM-DD y en ves de INPUT tipo text sean tipo date para aprovechar HTML5. puedo obtener el valor de un input date de esta manera var fechaInicial=document.getElementById("fechaInicial").value;
Responder
giancarlo
21 de Agosto del 2018
estrellaestrellaestrellaestrellaestrella
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
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
 
    <script>
    /**
	 * Documentado en http://lwp-l.com/s2379
	 */
	function isValidDate(day,month,year)
	{
		var dteDate;
		month=month-1;
		dteDate=new Date(year,month,day);
		return ((day==dteDate.getDate()) && (month==dteDate.getMonth()) && (year==dteDate.getFullYear()));
	}
 
	/**
	 * Funcion para validar una fecha
	 * Tiene que recibir:
	 *  La fecha en formato español dd/mm/yyyy
	 * Devuelve:
	 *  true o false
	 */
	function validate_fecha(fecha)
	{
		var patron=new RegExp("^(19|20)+([0-9]{2})([-])([0-9]{1,2})([-])([0-9]{1,2})$");
 
		if(fecha.search(patron)==0)
		{
			var values=fecha.split("-");
			if(isValidDate(values[2],values[1],values[0]))
			{
				return true;
			}
		}
		return false;
	}
 
    function calcularDias()
    {
		var fechaInicial=document.getElementById("fechaInicial").value;
		var fechaFinal=document.getElementById("fechaFinal").value;
		var resultado="";
		if(validate_fecha(fechaInicial) && validate_fecha(fechaFinal))
		{
			inicial=fechaInicial.split("-");
			final=fechaFinal.split("-");
			// obtenemos las fechas en milisegundos
			var dateStart=new Date(inicial[0],(inicial[1]-1),inicial[2]);
            var dateEnd=new Date(final[0],(final[1]-1),final[2]);
 
            if(dateStart<dateEnd)
            {
				// la diferencia entre las dos fechas, la dividimos entre 86400 segundos
				// que tiene un dia, y posteriormente entre 1000 ya que estamos
				// trabajando con milisegundos.
				var diasDif = dateEnd.getTime() - dateStart.getTime();
				resultado="Dias trancurridos: "+ (diasDif/86400000) +" ";
 
			}else{
				alert("La fecha inicial es posterior a la fecha final");
 
			}
		}else{
			if(!validate_fecha(fechaInicial))
				alert("La fecha inicial es incorrecta");
			if(!validate_fecha(fechaFinal))
				alert("La fecha final es incorrecta");
		}
		document.getElementById("resultado").innerHTML=resultado;
 
    }
    </script>
 
</head>
 
<body>
 
<form>
	<p>Introduce la fecha inicial y final en formato español dd/mm/yyyy</p>
	<input type="date" name="fechaInicial" id="fechaInicial" >
	<input type="date" name="fechaFinal" id="fechaFinal">
 
	<input type="button" value="Calcular dias" onclick="calcularDias();">
</form>
<div id="resultado"></div>
 
 
</body>
</html>
Responder
Imágen de perfil
14 de Junio del 2019
estrellaestrellaestrellaestrellaestrella
Esta perfecto con un input date pero yo queria armar algo que sea automatico no apretando el boton, se puede hacer ? xq estoy tirando codigos y no me cierra.
Responder
Luis Luzardo
14 de Diciembre del 2020
estrellaestrellaestrellaestrellaestrella
muy bueno
Responder

Comentar la versión: Versión 1

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s2718