HTML - Calculo de días entre dos fechas

 
Vista:
sin imagen de perfil

Calculo de días entre dos fechas

Publicado por Cristina (5 intervenciones) el 21/04/2016 18:09:35
Alguien sabe o tiene código en HTML, que me permita hacer el cálculo de días entre dos fechas?? Y como ir restando días a ese resultado
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
sin imagen de perfil

Calculo de días entre dos fechas

Publicado por Cristina (5 intervenciones) el 22/04/2016 00:58:38
Ya cale ese código lo que no puedo hacer es que el resultado me lo mande en un input...
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
Imágen de perfil de xve
Val: 1.144
Oro
Ha mantenido su posición en HTML (en relación al último mes)
Gráfica de HTML

Calculo de días entre dos fechas

Publicado por xve (1543 intervenciones) el 22/04/2016 08:58:36
Es casi lo mismo... nos puedes mostrar tu código y te indico como hacerlo...
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

Calculo de días entre dos fechas

Publicado por Cristina (5 intervenciones) el 22/04/2016 16:22:35
Este es mi código:
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
<!DOCTYPE>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" dir="ltr" lang="es" ><head>
	<meta http-equiv="Content-Style-Type" content="text/css" charset=utf-8 >
 
 
<script type="text/javascript">
function calculate(){
	document.getElementById("res_area").style.visibility="visible";
	var dt=document.getElementById("from_date").value;
	var dtt=document.getElementById("to_date").value;
	var dat=new Date(dt);
	var today=new Date(dtt);
	var diff=Math.ceil((today.getTime()-dat.getTime())/(1000*60*60*24));
	document.getElementById("result1").value=diff;
}
</script>
	    <div id="input">
 
			<tr><td colspan="2" align="center" valign="top" id="title"><h2> Fecha de cálculo de la diferencia</h2></td></tr>
			<tr><td valign="top"><label>Desde la fecha </label></td><td><input type="text" id="from_date" name="from_date" value="">
 
			</label>
            <br />
            <br />&nbsp;</td></tr><label>Hasta la fecha</label></td><td><input type="text"
                id="to_date" name="from_date1" value="" size="20">
 
			</label>
            <br />
            <br />&nbsp;</td></tr>
 
			<tr><td align="center"></td><td><input type="button" value="Calcular" id="button" onClick="calculate()"></td><td></td></tr>
			 <script type="text/javascript">
	var s=new Date();
	document.getElementById("to_date").value=(s.getMonth()+1)+'/'+s.getDate()+'/'+s.getFullYear();
	document.getElementById("from_date").value=(s.getMonth()+1)+'/'+s.getDate()+'/'+(s.getFullYear()-1);
</script>
 
		    <br />
            <br />
 
		<div id="res_area" style="width:90%">
			<tr><td class="style1"><label>Fecha de diferencia</label></td><td class="style1">&nbsp; <input type="text" disabled="disabled"  class="result" id="result1" size="2" /> <label id="unit">Días</label></td></tr>
 
	 </div>
	 	</div>
			<script type="text/javascript">
			for(i=1;i<=20;i++){
				try{
					var re=document.getElementById("result"+i);
					re.disabled=false;
				}
				catch(e){
					break;
				}
			}
		</script>
 
 
	</td></tr>
	</table>
	<br />
 
 
 
  </td>
 
 
 
  </td>
  </tr>
  </table>
 
 
 
	</div>
		</div>
 
</div>
 
</body></html>


Más no se si se pueda o sepan para que me serviria esta función, segun yo es para lo mismo que tengo en la parte de arriva:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Función que suma o resta días a la fecha indicada
 
sumaFecha = function(d, fecha)
{
 var Fecha = new Date();
 var sFecha = fecha || (Fecha.getDate() + "/" + (Fecha.getMonth() +1) + "/" + Fecha.getFullYear());
 var sep = sFecha.indexOf('/') != -1 ? '/' : '-';
 var aFecha = sFecha.split(sep);
 var fecha = aFecha[2]+'/'+aFecha[1]+'/'+aFecha[0];
 fecha= new Date(fecha);
 fecha.setDate(fecha.getDate()+parseInt(d));
 var anno=fecha.getFullYear();
 var mes= fecha.getMonth()+1;
 var dia= fecha.getDate();
 mes = (mes < 10) ? ("0" + mes) : mes;
 dia = (dia < 10) ? ("0" + dia) : dia;
 var fechaFinal = dia+sep+mes+sep+anno;
 return (fechaFinal);
 }
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
Imágen de perfil de xve
Val: 1.144
Oro
Ha mantenido su posición en HTML (en relación al último mes)
Gráfica de HTML

Calculo de días entre dos fechas

Publicado por xve (1543 intervenciones) el 22/04/2016 16:59:02
Hola Cristina, tu código funciona perfectamente, lo único, que pones la fecha en un formato erróneo!!!

tienes que poner las fechas así: yyyy/mm/dd y te funcionará perfectamente!!!
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

Calculo de días entre dos fechas

Publicado por juan (3 intervenciones) el 12/08/2024 06:16:14
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
<?php
 
 
$data = [
    [
        'id' => 1,
        'nombre' => 'Diego',
        'fecha' => '05-06-1998',
        'estado' => 1,
        'imagen' => 'img/im1.png'
    ],
    [
        'id' => 2,
        'nombre' => 'Sam',
        'fecha' => '02-05-1999',
        'estado' => 0,
        'imagen' => 'img/im2.png'
    ],
    [
        'id' => 3,
        'nombre' => 'Pedro',
        'fecha' => '01-11-1980',
        'estado' => 0,
        'imagen' => 'img/im3.png'
    ]
];
 
function obtener_edad_segun_fecha($fecha_nacimiento) {
    $nacimiento = new DateTime($fecha_nacimiento);
    $ahora = new DateTime(date("Y-m-d"));
    $diferencia = $ahora->diff($nacimiento);
    return $diferencia->format("%y");
}
 
function es_mayor_de_edad($fecha_nacimiento) {
    return obtener_edad_segun_fecha($fecha_nacimiento) >= 18;
}
 
$json_data = json_encode($data);
?>
 
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestión de Personas</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
 
    <div class="contenedor-total">
        <div class="tablaYForm">
            <table id="tabla-personas">
                <thead>
                    <h1>Gestión de usuarios</h1>
                    <tr>
                        <th>ID</th>
                        <th>Nombre</th>
                        <th>Fecha</th>
                        <th>Estado</th>
                        <th>Acción</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($data as $persona): ?>
                        <tr>
                            <td><?php echo $persona['id']; ?></td>
                            <td><?php echo $persona['nombre']; ?></td>
                            <td><?php echo $persona['fecha']; ?></td>
                            <td>
                                <span id="estado-<?php echo $persona['id']; ?>"
                                      class="btn-estado <?php echo $persona['estado'] ? 'activo' : 'inactivo'; ?>">
                                    <?php echo $persona['estado'] ? 'Activo' : 'Inactivo'; ?>
                                </span>
                            </td>
                            <td>
                                <button class="btn-ver" onclick="verTarjeta(<?php echo htmlspecialchars(json_encode($persona)); ?>)">
                                    Ver
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <h2>Registro usuarios</h2>
            <form id="formulario-persona" onsubmit="return guardarPersona()">
                <input type="hidden" id="inputId" name="id">
                <label for="userId">ID:</label>
                <input type="text" id="userId" readonly>
                <label for="inputNombre">Nombre:</label>
                <input id="inputNombre" type="text" name="nombre" required>
                <label for="inputFecha">Fecha de Nacimiento:</label>
                <input id="inputFecha" type="date" name="fecha" required>
                <label for="inputEstado">Estado:</label>
                <select id="inputEstado" name="estado" required>
                    <option value="1">Activo</option>
                    <option value="0">Inactivo</option>
                </select>
                <input type="submit" value="Guardar">
            </form>
        </div>
 
        <div class="tarjeta">
            <img id="foto-tarjeta" src="img/foto.png" alt="Foto de perfil">
            <h3 id="nombre-tarjeta">...</h3>
            <p id="edad-tarjeta">Edad</p>
        </div>
    </div>
 
    <script>
    let personas = <?php echo $json_data; ?>;
    </script>
    <script src="script.js"></script>
</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
sin imagen de perfil

Calculo de días entre dos fechas

Publicado por juan (3 intervenciones) el 12/08/2024 06:17:04
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
let ultimoId = Math.max(...personas.map(p => p.id));
 
function verTarjeta(persona) {
    document.getElementById('foto-tarjeta').src = persona.imagen;
    document.getElementById('nombre-tarjeta').textContent = persona.nombre;
 
    const fechaArray = persona.fecha.split('-');
    const fechaNacimiento = new Date(`${fechaArray[2]}-${fechaArray[1]}-${fechaArray[0]}`);
    const edad = calcularEdad(fechaNacimiento);
 
    document.getElementById('edad-tarjeta').textContent = `${edad} Años`;
 
    document.getElementById('inputId').value = persona.id;
    document.getElementById('inputNombre').value = persona.nombre;
    document.getElementById('inputFecha').value = `${fechaArray[2]}-${fechaArray[1]}-${fechaArray[0]}`;
    document.getElementById('inputEstado').value = persona.estado;
}
 
function calcularEdad(fechaNacimiento) {
    const hoy = new Date();
    let edad = hoy.getFullYear() - fechaNacimiento.getFullYear();
    const mes = hoy.getMonth() - fechaNacimiento.getMonth();
 
    if (mes < 0 || (mes === 0 && hoy.getDate() < fechaNacimiento.getDate())) {
        edad--;
    }
 
    return edad;
}
 
function guardarPersona() {
    const id = document.getElementById('inputId').value;
    const nombre = document.getElementById('inputNombre').value;
    const fecha = document.getElementById('inputFecha').value;
    const estado = document.getElementById('inputEstado').value;
 
    const fechaNacimiento = new Date(fecha);
    const edad = calcularEdad(fechaNacimiento);
 
    if (edad < 18) {
        alert(`No se puede guardar. La persona tiene ${edad} años y no es mayor de edad.`);
        return false;
    }
 
    const fechaFormateada = `${fecha.slice(8, 10)}-${fecha.slice(5, 7)}-${fecha.slice(0, 4)}`;
 
    if (id) {
        // Actualizar persona existente
        const index = personas.findIndex(p => p.id == id);
        if (index !== -1) {
            personas[index] = { ...personas[index], nombre, fecha: fechaFormateada, estado: parseInt(estado) };
            actualizarTabla();
        }
    } else {
        // Agregar nueva persona
        ultimoId++;
        const nuevaPersona = {
            id: ultimoId,
            nombre,
            fecha: fechaFormateada,
            estado: parseInt(estado),
            imagen: 'img/default.png'
        };
        personas.push(nuevaPersona);
        actualizarTabla();
    }
 
    document.getElementById('formulario-persona').reset();
    document.getElementById('inputId').value = '';
    return false;
}
 
function actualizarTabla() {
    const tbody = document.querySelector('#tabla-personas tbody');
    tbody.innerHTML = '';
 
    personas.forEach(persona => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${persona.id}</td>
            <td>${persona.nombre}</td>
            <td>${persona.fecha}</td>
            <td>
                <span id="estado-${persona.id}"
                      class="btn-estado ${persona.estado ? 'activo' : 'inactivo'}">
                    ${persona.estado ? 'Activo' : 'Inactivo'}
                </span>
            </td>
            <td>
                <button class="btn-ver" onclick="verTarjeta(${JSON.stringify(persona)})">
                    Ver
                </button>
            </td>
        `;
        tbody.appendChild(tr);
    });
}
 
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.btn-estado').forEach(btn => {
        btn.addEventListener('click', function() {
            const id = this.id.split('-')[1];
            const persona = personas.find(p => p.id == id);
            if (persona) {
                persona.estado = !persona.estado;
                this.textContent = persona.estado ? 'Activo' : 'Inactivo';
                this.className = `btn-estado ${persona.estado ? 'activo' : 'inactivo'}`;
            }
        });
    });
});
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

Calculo de días entre dos fechas

Publicado por juan (3 intervenciones) el 12/08/2024 06:18:06
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
body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 20px;
    background-color: #f0f0f0;
}
 
.contenedor-total {
    display: flex;
    justify-content: space-between;
    max-width: 1200px;
    margin: 0 auto;
}
 
.tablaYForm {
    width: 60%;
}
 
table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 20px;
    background-color: white;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
 
th, td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: center; /* Centra el contenido de las celdas */
    font-size: 14px;
}
 
th {
    background-color: #4ca3b9;
    color: white;
}
 
tr:hover {
    background-color: #f5f5f5;
}
 
.btn-estado {
    padding: 5px 10px;
    border-radius: 10px;
    color: white;
    cursor: pointer;
}
 
.activo {
    background-color: #4CAF50;
}
 
.inactivo {
    background-color: #fa1707;
}
button:hover {
    background-color: #333;
    color: white;
}
 
.btn-ver {
    background-color: #0a9ecf;
    border: none;
    color: white;
    padding: 5px 10px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 14px;
    margin: 4px 2px;
    cursor: pointer;
    border-radius: 4px;
}
 
form {
    display: flex;
    align-items: center;
    flex-direction: column;
    background-color: white;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
 
    width: 60%;
     margin: 0 auto;
    border: 1px solid #ddd;
 
}
 
form label {
    margin-top: 10px;
    font-size: 16px;
    font-weight: bold;
 
}
 
form input, form select {
    padding: 10px;
    margin-top: 5px;
    width: 60%;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
 
}
 
form input[type="submit"] {
    background-color: #a0bb29;
    color: white;
    border: none;
    padding: 10px;
    cursor: pointer;
}
 
.tarjeta {
    width: 35%;
    border: 2px solid #ddd;
    border-radius: 10px;
    padding: 20px;
    text-align: center;
    background-color: white;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
 
.tarjeta img {
    width: 200px;
    height: 200px;
    border-radius: 50%;
    object-fit: cover;
    margin-bottom: 15px;
}
 
.tarjeta h3 {
    margin: 10px 0;
    color: #333;
}
 
.tarjeta p {
    color: #666;
    font-size: 18px;
}
 
h1, h2{
    color: #010d0e;
    font-size: 20px;
    text-align: center;
}
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