Skip to content

Commit bdae4f9

Browse files
authored
Merge pull request mouredev#6393 from eulogioep/main
#14 - java, javascript, php y typescript
2 parents c0b89a1 + 2c99a4b commit bdae4f9

File tree

4 files changed

+350
-0
lines changed

4 files changed

+350
-0
lines changed
+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import java.time.LocalDateTime;
2+
import java.time.format.DateTimeFormatter;
3+
import java.time.temporal.ChronoUnit;
4+
import java.time.Month;
5+
import java.time.DayOfWeek;
6+
7+
public class eulogioep {
8+
public static void main(String[] args) {
9+
// PARTE 1: Crear variables de fecha y calcular años transcurridos
10+
11+
// Creamos la fecha actual usando LocalDateTime.now()
12+
LocalDateTime fechaActual = LocalDateTime.now();
13+
14+
// Creamos una fecha de nacimiento (ejemplo)
15+
LocalDateTime fechaNacimiento = LocalDateTime.of(1990, 5, 15, 14, 30, 0);
16+
17+
// Calculamos los años transcurridos entre ambas fechas
18+
long añosTranscurridos = ChronoUnit.YEARS.between(fechaNacimiento, fechaActual);
19+
20+
System.out.println("Fecha actual: " + fechaActual);
21+
System.out.println("Fecha de nacimiento: " + fechaNacimiento);
22+
System.out.println("Años transcurridos: " + añosTranscurridos);
23+
24+
// PARTE 2: DIFICULTAD EXTRA - Formatear la fecha de 10 maneras diferentes
25+
26+
System.out.println("\nDIFERENTES FORMATOS DE FECHA:");
27+
28+
// 1. Día, mes y año
29+
DateTimeFormatter fmt1 = DateTimeFormatter.ofPattern("dd/MM/yyyy");
30+
System.out.println("1. Día, mes y año: " + fechaNacimiento.format(fmt1));
31+
32+
// 2. Hora, minuto y segundo
33+
DateTimeFormatter fmt2 = DateTimeFormatter.ofPattern("HH:mm:ss");
34+
System.out.println("2. Hora, minuto y segundo: " + fechaNacimiento.format(fmt2));
35+
36+
// 3. Día del año
37+
System.out.println("3. Día del año: " + fechaNacimiento.getDayOfYear());
38+
39+
// 4. Día de la semana
40+
System.out.println("4. Día de la semana: " + fechaNacimiento.getDayOfWeek());
41+
42+
// 5. Nombre del mes
43+
System.out.println("5. Nombre del mes: " + fechaNacimiento.getMonth());
44+
45+
// 6. Formato largo con día de la semana
46+
DateTimeFormatter fmt6 = DateTimeFormatter.ofPattern("EEEE, d 'de' MMMM 'de' yyyy");
47+
System.out.println("6. Formato largo: " + fechaNacimiento.format(fmt6));
48+
49+
// 7. Formato corto de 12 horas
50+
DateTimeFormatter fmt7 = DateTimeFormatter.ofPattern("dd-MM-yy hh:mm a");
51+
System.out.println("7. Formato 12 horas: " + fechaNacimiento.format(fmt7));
52+
53+
// 8. Semana del año
54+
System.out.println("8. Semana del año: " + (fechaNacimiento.getDayOfYear() / 7 + 1));
55+
56+
// 9. Trimestre del año
57+
System.out.println("9. Trimestre del año: " + ((fechaNacimiento.getMonthValue() - 1) / 3 + 1));
58+
59+
// 10. ISO fecha y hora
60+
System.out.println("10. Formato ISO: " + fechaNacimiento.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
61+
}
62+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
// Ejercicio de manejo de fechas en JavaScript
2+
3+
// PARTE 1: Crear variables de fecha y calcular años transcurridos
4+
5+
// Creamos la fecha actual
6+
const fechaActual = new Date();
7+
8+
// Creamos una fecha de nacimiento (ejemplo)
9+
const fechaNacimiento = new Date(1990, 4, 15, 14, 30, 0); // Mes 4 es Mayo (0-11)
10+
11+
// Calculamos los años transcurridos
12+
const añosTranscurridos = fechaActual.getFullYear() - fechaNacimiento.getFullYear();
13+
14+
// Ajustamos si aún no hemos llegado al mes y día de nacimiento este año
15+
if (
16+
fechaActual.getMonth() < fechaNacimiento.getMonth() ||
17+
(fechaActual.getMonth() === fechaNacimiento.getMonth() &&
18+
fechaActual.getDate() < fechaNacimiento.getDate())
19+
) {
20+
añosTranscurridos--;
21+
}
22+
23+
console.log("Fecha actual:", fechaActual.toLocaleString());
24+
console.log("Fecha de nacimiento:", fechaNacimiento.toLocaleString());
25+
console.log("Años transcurridos:", añosTranscurridos);
26+
27+
// PARTE 2: DIFICULTAD EXTRA - Formatear la fecha de 10 maneras diferentes
28+
29+
console.log("\nDIFERENTES FORMATOS DE FECHA:");
30+
31+
// 1. Día, mes y año
32+
console.log("1. Día, mes y año:", fechaNacimiento.toLocaleDateString());
33+
34+
// 2. Hora, minuto y segundo
35+
console.log("2. Hora, minuto y segundo:", fechaNacimiento.toLocaleTimeString());
36+
37+
// 3. Día del año
38+
const inicioDeLAño = new Date(fechaNacimiento.getFullYear(), 0, 0);
39+
const diff = fechaNacimiento - inicioDeLAño;
40+
const unDiaEnMs = 1000 * 60 * 60 * 24;
41+
const diaDelAño = Math.floor(diff / unDiaEnMs);
42+
console.log("3. Día del año:", diaDelAño);
43+
44+
// 4. Día de la semana
45+
const diasSemana = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
46+
console.log("4. Día de la semana:", diasSemana[fechaNacimiento.getDay()]);
47+
48+
// 5. Nombre del mes
49+
const meses = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
50+
console.log("5. Nombre del mes:", meses[fechaNacimiento.getMonth()]);
51+
52+
// 6. Formato largo personalizado
53+
console.log("6. Formato largo:", `${diasSemana[fechaNacimiento.getDay()]}, ${fechaNacimiento.getDate()} de ${meses[fechaNacimiento.getMonth()]} de ${fechaNacimiento.getFullYear()}`);
54+
55+
// 7. Formato ISO
56+
console.log("7. Formato ISO:", fechaNacimiento.toISOString());
57+
58+
// 8. Formato de 12 horas
59+
console.log("8. Formato 12 horas:", fechaNacimiento.toLocaleTimeString('es-ES', { hour12: true }));
60+
61+
// 9. Timestamp Unix
62+
console.log("9. Timestamp Unix:", Math.floor(fechaNacimiento.getTime() / 1000));
63+
64+
// 10. Trimestre del año
65+
const trimestre = Math.floor(fechaNacimiento.getMonth() / 3) + 1;
66+
console.log("10. Trimestre del año:", trimestre);
67+
68+
// Función auxiliar para formatear números con ceros iniciales
69+
function padZero(num) {
70+
return num.toString().padStart(2, '0');
71+
}

Roadmap/14 - FECHAS/php/eulogioep.php

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
<?php
2+
/**
3+
* Ejercicio de manejo de fechas en PHP
4+
* Este script demuestra diferentes operaciones y formatos con fechas
5+
*/
6+
7+
// PARTE 1: Crear variables de fecha y calcular años transcurridos
8+
9+
// Creamos la fecha actual
10+
$fechaActual = new DateTime();
11+
12+
// Creamos una fecha de nacimiento (ejemplo)
13+
$fechaNacimiento = new DateTime('1990-05-15 14:30:00');
14+
15+
// Calculamos la diferencia entre las fechas
16+
$diferencia = $fechaActual->diff($fechaNacimiento);
17+
18+
echo "Fecha actual: " . $fechaActual->format('Y-m-d H:i:s') . "\n";
19+
echo "Fecha de nacimiento: " . $fechaNacimiento->format('Y-m-d H:i:s') . "\n";
20+
echo "Años transcurridos: " . $diferencia->y . "\n\n";
21+
22+
// PARTE 2: DIFICULTAD EXTRA - Formatear la fecha de 10 maneras diferentes
23+
24+
echo "DIFERENTES FORMATOS DE FECHA:\n";
25+
26+
// 1. Día, mes y año
27+
echo "1. Día, mes y año: " . $fechaNacimiento->format('d/m/Y') . "\n";
28+
29+
// 2. Hora, minuto y segundo
30+
echo "2. Hora, minuto y segundo: " . $fechaNacimiento->format('H:i:s') . "\n";
31+
32+
// 3. Día del año
33+
echo "3. Día del año: " . $fechaNacimiento->format('z') . " (comenzando desde 0)\n";
34+
35+
// 4. Día de la semana
36+
$diasSemana = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
37+
echo "4. Día de la semana: " . $diasSemana[$fechaNacimiento->format('w')] . "\n";
38+
39+
// 5. Nombre del mes
40+
$meses = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio',
41+
'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
42+
echo "5. Nombre del mes: " . $meses[$fechaNacimiento->format('n') - 1] . "\n";
43+
44+
// 6. Formato largo personalizado
45+
setlocale(LC_TIME, 'es_ES.UTF-8');
46+
echo "6. Formato largo: " . strftime('%A, %d de %B de %Y', $fechaNacimiento->getTimestamp()) . "\n";
47+
48+
// 7. Formato ISO 8601
49+
echo "7. Formato ISO 8601: " . $fechaNacimiento->format('c') . "\n";
50+
51+
// 8. Semana del año
52+
echo "8. Semana del año: " . $fechaNacimiento->format('W') . "\n";
53+
54+
// 9. Trimestre del año
55+
$trimestre = ceil($fechaNacimiento->format('n') / 3);
56+
echo "9. Trimestre del año: " . $trimestre . "\n";
57+
58+
// 10. Timestamp Unix
59+
echo "10. Timestamp Unix: " . $fechaNacimiento->getTimestamp() . "\n";
60+
61+
// Funciones auxiliares de ejemplo
62+
function obtenerEdad($fechaNacimiento) {
63+
$hoy = new DateTime();
64+
$edad = $hoy->diff($fechaNacimiento);
65+
return $edad->y;
66+
}
67+
68+
function esBisiesto($año) {
69+
return date('L', strtotime("$año-01-01")) == 1;
70+
}
71+
72+
// Ejemplo de uso de funciones auxiliares
73+
echo "\nFUNCIONES AUXILIARES:\n";
74+
echo "Edad calculada: " . obtenerEdad($fechaNacimiento) . " años\n";
75+
echo "¿El año de nacimiento es bisiesto? " .
76+
(esBisiesto($fechaNacimiento->format('Y')) ? "" : "No") . "\n";
77+
?>
+140
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
// Definimos algunas interfaces útiles
2+
interface DateFormats {
3+
dayMonthYear: string;
4+
hourMinuteSecond: string;
5+
dayOfYear: number;
6+
dayOfWeek: string;
7+
monthName: string;
8+
longFormat: string;
9+
isoFormat: string;
10+
twelveHourFormat: string;
11+
unixTimestamp: number;
12+
quarterOfYear: number;
13+
}
14+
15+
// Definimos algunos tipos de utilidad
16+
type MonthName = 'Enero' | 'Febrero' | 'Marzo' | 'Abril' | 'Mayo' | 'Junio' |
17+
'Julio' | 'Agosto' | 'Septiembre' | 'Octubre' | 'Noviembre' | 'Diciembre';
18+
type DayOfWeek = 'Domingo' | 'Lunes' | 'Martes' | 'Miércoles' | 'Jueves' | 'Viernes' | 'Sábado';
19+
20+
// Creamos algunas constantes con tipos
21+
const DAYS_OF_WEEK: DayOfWeek[] = [
22+
'Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'
23+
];
24+
25+
const MONTHS: MonthName[] = [
26+
'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio',
27+
'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'
28+
];
29+
30+
class DateCalculator {
31+
private currentDate: Date;
32+
private birthDate: Date;
33+
34+
constructor(birthDate: Date) {
35+
this.currentDate = new Date();
36+
this.birthDate = birthDate;
37+
}
38+
39+
calculateYearsBetween(): number {
40+
let years = this.currentDate.getFullYear() - this.birthDate.getFullYear();
41+
const currentMonth = this.currentDate.getMonth();
42+
const birthMonth = this.birthDate.getMonth();
43+
44+
// Ajustamos si aún no hemos llegado al mes y día de nacimiento este año
45+
if (currentMonth < birthMonth ||
46+
(currentMonth === birthMonth &&
47+
this.currentDate.getDate() < this.birthDate.getDate())) {
48+
years--;
49+
}
50+
51+
return years;
52+
}
53+
54+
formatDates(): DateFormats {
55+
return {
56+
dayMonthYear: this.formatDate(this.birthDate, 'dd/MM/yyyy'),
57+
hourMinuteSecond: this.formatTime(this.birthDate),
58+
dayOfYear: this.getDayOfYear(this.birthDate),
59+
dayOfWeek: DAYS_OF_WEEK[this.birthDate.getDay()],
60+
monthName: MONTHS[this.birthDate.getMonth()],
61+
longFormat: this.getLongFormat(this.birthDate),
62+
isoFormat: this.birthDate.toISOString(),
63+
twelveHourFormat: this.get12HourFormat(this.birthDate),
64+
unixTimestamp: Math.floor(this.birthDate.getTime() / 1000),
65+
quarterOfYear: Math.floor(this.birthDate.getMonth() / 3) + 1
66+
};
67+
}
68+
69+
private formatDate(date: Date, format: string): string {
70+
const day = String(date.getDate()).padStart(2, '0');
71+
const month = String(date.getMonth() + 1).padStart(2, '0');
72+
const year = date.getFullYear();
73+
74+
return format
75+
.replace('dd', day)
76+
.replace('MM', month)
77+
.replace('yyyy', String(year));
78+
}
79+
80+
private formatTime(date: Date): string {
81+
return date.toLocaleTimeString('es-ES', {
82+
hour12: false,
83+
hour: '2-digit',
84+
minute: '2-digit',
85+
second: '2-digit'
86+
});
87+
}
88+
89+
private getDayOfYear(date: Date): number {
90+
const startOfYear = new Date(date.getFullYear(), 0, 0);
91+
const diff = date.getTime() - startOfYear.getTime();
92+
const oneDay = 1000 * 60 * 60 * 24;
93+
return Math.floor(diff / oneDay);
94+
}
95+
96+
private getLongFormat(date: Date): string {
97+
const dayOfWeek = DAYS_OF_WEEK[date.getDay()];
98+
const dayOfMonth = date.getDate();
99+
const month = MONTHS[date.getMonth()];
100+
const year = date.getFullYear();
101+
102+
return `${dayOfWeek}, ${dayOfMonth} de ${month} de ${year}`;
103+
}
104+
105+
private get12HourFormat(date: Date): string {
106+
return date.toLocaleTimeString('es-ES', { hour12: true });
107+
}
108+
}
109+
110+
// Uso del código
111+
const birthDate = new Date(1990, 4, 15, 14, 30, 0); // Mes 4 es Mayo (0-11)
112+
const calculator = new DateCalculator(birthDate);
113+
114+
// PARTE 1: Calcular años transcurridos
115+
const yearsPassedTesting = (): void => {
116+
console.log('Fecha actual:', new Date().toLocaleString());
117+
console.log('Fecha de nacimiento:', birthDate.toLocaleString());
118+
console.log('Años transcurridos:', calculator.calculateYearsBetween());
119+
};
120+
121+
// PARTE 2: Mostrar diferentes formatos de fecha
122+
const showFormattedDates = (): void => {
123+
const formats = calculator.formatDates();
124+
125+
console.log('\nDIFERENTES FORMATOS DE FECHA:');
126+
console.log('1. Día, mes y año:', formats.dayMonthYear);
127+
console.log('2. Hora, minuto y segundo:', formats.hourMinuteSecond);
128+
console.log('3. Día del año:', formats.dayOfYear);
129+
console.log('4. Día de la semana:', formats.dayOfWeek);
130+
console.log('5. Nombre del mes:', formats.monthName);
131+
console.log('6. Formato largo:', formats.longFormat);
132+
console.log('7. Formato ISO:', formats.isoFormat);
133+
console.log('8. Formato 12 horas:', formats.twelveHourFormat);
134+
console.log('9. Unix Timestamp:', formats.unixTimestamp);
135+
console.log('10. Trimestre del año:', formats.quarterOfYear);
136+
};
137+
138+
// Ejecutamos las funciones
139+
yearsPassedTesting();
140+
showFormattedDates();

0 commit comments

Comments
 (0)