Skip to content

Commit c7b9b3b

Browse files
#14 - javascript
1 parent 7722a8e commit c7b9b3b

File tree

1 file changed

+283
-0
lines changed

1 file changed

+283
-0
lines changed
Lines changed: 283 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,283 @@
1+
/*
2+
* EJERCICIO #14 FECHAS:
3+
* Crea dos variables utilizando los objetos fecha (date, o semejante) de tu lenguaje:
4+
* - Una primera que represente la fecha (día, mes, año, hora, minuto, segundo) actual.
5+
* - Una segunda que represente tu fecha de nacimiento (te puedes inventar la hora).
6+
* Calcula cuántos años han transcurrido entre ambas fechas.
7+
*
8+
* DIFICULTAD EXTRA (opcional):
9+
* Utilizando la fecha de tu cumpleaños, formatéala y muestra su resultado de
10+
* 10 maneras diferentes. Por ejemplo:
11+
* - Día, mes y año.
12+
* - Hora, minuto y segundo.
13+
* - Día de año.
14+
* - Día de la semana.
15+
* - Nombre del mes.
16+
* (lo que se te ocurra...)
17+
*/
18+
19+
// bibliography
20+
//Professional JavaScript for web developers by Matt Frisbie [Frisbie, Matt] (z-lib.org)
21+
//GPT
22+
23+
24+
// short for console.log()
25+
let log = console.log;
26+
27+
window.addEventListener('load', ()=>{
28+
const body = document.querySelector('body');
29+
const title = document.createElement('h1');
30+
31+
body.style.setProperty('background', '#000');
32+
body.style.setProperty('text-align', 'center');
33+
34+
title.textContent = 'Retosparaprogramadores #14.';
35+
title.style.setProperty('font-size', '3.5vmax');
36+
title.style.setProperty('color', '#fff');
37+
title.style.setProperty('line-height', '100vh');
38+
39+
body.appendChild(title);
40+
41+
setTimeout(()=>{
42+
alert('Retosparaprogramadores #14. Please open the Browser Developer Tools.');
43+
}, 2000);
44+
log( 'Retosparaprogramadores #14');
45+
});
46+
47+
48+
let today = new Date()
49+
log(today); // Date Fri Oct 18 2024 10:24:48 GMT-0400 (Venezuela Time)
50+
log(today.toDateString()); // Fri Oct 18 2024
51+
let myBirthday = new Date(Date.parse("1983-08-08T08:30:00"));
52+
log(myBirthday); // Date Mon Aug 08 1983 08:30:00 GMT-0400 (Venezuela Time)
53+
log(myBirthday.toLocaleDateString()); // 8/8/1983
54+
log(myBirthday.toLocaleString()); // 8/8/1983, 8:30:00 AM
55+
56+
const calcYearsBetween = (date1, date2) => {
57+
if (date1 < date2) {
58+
[date1, date2] = [date2, date1]; // Swap if date1 is earlier
59+
}
60+
61+
const differenceInMilliseconds = date1.getTime() - date2.getTime();
62+
63+
const years = differenceInMilliseconds / (1000 * 60 * 60 * 24 * 365.25);
64+
65+
let fullYears = Math.floor(years);
66+
67+
// Check if the anniversary has not yet occurred this year
68+
if (
69+
date1.getMonth() < date2.getMonth() ||
70+
(date1.getMonth() === date2.getMonth() && date1.getDate() < date2.getDate())
71+
) {
72+
fullYears--;
73+
}
74+
return years;
75+
};
76+
77+
// Note: By incorporating the anniversary check, the function provides a more accurate representation of the year difference.
78+
79+
80+
// Note: Using 365.25 rather than 365 allows for greater precision because it accounts for leap years.
81+
82+
const yearsBetween = calcYearsBetween(today, myBirthday);
83+
log(`Years between: ${yearsBetween.toFixed(2)}`); // 41.20
84+
85+
86+
//or just
87+
const calcYearsBetween2 = (date1, date2) => {
88+
if (date1 < date2) {
89+
[date1, date2] = [date2, date1]; // Swap if date1 is earlier
90+
}
91+
const years = date1.getFullYear() - date2.getFullYear();
92+
93+
if (
94+
date1.getMonth() < date2.getMonth() ||
95+
(date1.getMonth() === date2.getMonth() && date1.getDate() < date2.getDate())
96+
) {
97+
years--;
98+
}
99+
100+
return years;
101+
};
102+
103+
log(calcYearsBetween2(today, myBirthday)); // 41
104+
105+
106+
107+
const calcDateDifference = (date1, date2) => {
108+
// Ensure date1 is the later date
109+
if (date1 < date2) {
110+
[date1, date2] = [date2, date1]; // Swap if date1 is earlier
111+
}
112+
113+
// Calculate the difference in milliseconds
114+
const differenceInMilliseconds = date1.getTime() - date2.getTime();
115+
116+
// Calculate total seconds
117+
const totalSeconds = Math.floor(differenceInMilliseconds / 1000);
118+
119+
// Calculate total minutes
120+
const totalMinutes = Math.floor(totalSeconds / 60);
121+
122+
// Calculate total hours
123+
const totalHours = Math.floor(totalMinutes / 60);
124+
125+
// Calculate total days
126+
const totalDays = Math.floor(totalHours / 24);
127+
128+
// Calculate years, months, weeks, and remaining days
129+
const years = date1.getFullYear() - date2.getFullYear();
130+
const months = date1.getMonth() - date2.getMonth() + (years * 12);
131+
const weeks = Math.floor(totalDays / 7);
132+
const days = totalDays % 7;
133+
134+
// Calculate remaining hours, minutes, and seconds
135+
const remainingHours = totalHours % 24;
136+
const remainingMinutes = totalMinutes % 60;
137+
const remainingSeconds = totalSeconds % 60;
138+
139+
return {
140+
years,
141+
months,
142+
weeks,
143+
days,
144+
hours: remainingHours,
145+
minutes: remainingMinutes,
146+
seconds: remainingSeconds
147+
};
148+
};
149+
150+
151+
const difference = calcDateDifference(today, myBirthday);
152+
log(`Difference:
153+
${difference.years} years,
154+
${difference.months} months,
155+
${difference.weeks} weeks,
156+
${difference.days} days,
157+
${difference.hours} hours,
158+
${difference.minutes} minutes,
159+
${difference.seconds} seconds`);
160+
161+
/* Difference:
162+
41 years,
163+
494 months,
164+
2149 weeks,
165+
4 days,
166+
6 hours,
167+
28 minutes,
168+
38 seconds */
169+
170+
171+
// Extra dificulty Exercise
172+
173+
const formatBirthday = (birthday) => {
174+
const date = new Date(birthday);
175+
176+
const dayMonthYear = date.toLocaleDateString('en-US', { day: 'numeric', month: 'long', year: 'numeric' });
177+
178+
const time = date.toLocaleTimeString('es-ES', { hour: 'numeric', minute: 'numeric', second: 'numeric' });
179+
180+
const dayOfYear = Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
181+
182+
const dayOfWeek = date.toLocaleDateString('en-US', { weekday: 'long' });
183+
184+
const monthName = date.toLocaleDateString('en-US', { month: 'long' });
185+
186+
const isoFormat = date.toISOString();
187+
188+
const shortFormat = date.toLocaleDateString('en-US');
189+
190+
const longFormat = date.toLocaleDateString('en-US', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
191+
192+
const time12Hour = date.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: true });
193+
194+
const timeWithTimezone = date.toLocaleString('es-ES', { timeZoneName: 'short' });
195+
196+
log("1. I was born on:", dayMonthYear);
197+
log("2. at:", time + ' AM');
198+
log("3. the day:", dayOfYear + ' of the year ' + date.getFullYear());
199+
log("4. on:", dayOfWeek);
200+
log("5. one special day of:", monthName);
201+
log("6. isoFormat:", isoFormat);
202+
log("7. shortFormat:", shortFormat);
203+
log("8. longFormat:", longFormat);
204+
log("9. time12hour:", time12Hour);
205+
log("10. timeWithTimezone:", timeWithTimezone);
206+
};
207+
208+
formatBirthday(myBirthday);
209+
/*
210+
1. I was born on: August 8, 1983
211+
2. at: 8:30:00 AM
212+
3. the day: 220 of the year 1983
213+
4. on: Monday
214+
5. one special day of: August
215+
6. isoFormat: 1983-08-08T12:30:00.000Z
216+
7. shortFormat: 8/8/1983
217+
8. longFormat: Monday, August 8, 1983
218+
9. time12hour: 8:30:00 AM
219+
10. timeWithTimezone: 8/8/1983, 8:30:00 GMT-4 */
220+
221+
222+
223+
//REFERENCE INFORMATION:
224+
225+
226+
/* Date-Formatting Methods
227+
There are several Date type methods used specifically to format the date as a string. They are
228+
as follows:
229+
➤➤ toDateString()—Displays the date’s day of the week, month, day of the month, and year in
230+
an implementation-specific format.
231+
➤➤ toTimeString()—Displays the date’s hours, minutes, seconds, and time zone in an imple-
232+
mentation-specific format.
233+
➤➤ toLocaleDateString()—Displays the date’s day of the week, month, day of the month, and
234+
year in an implementation- and locale-specific format.
235+
➤➤ toLocaleTimeString()—Displays the date’s hours, minutes, and seconds in an implementa-
236+
tion-specific format.
237+
➤➤ toUTCString()—Displays the complete UTC date in an implementation-specific format.
238+
The output of these methods, as with toLocaleString() and toString(), varies widely from
239+
browser to browser and therefore can’t be employed in a user interface for consistent display of a date.
240+
241+
NOTE There is also a method called toGMTString(), which is equivalent to toUTCString() and is provided for backwards compatibility. However, the specification recommends that new code use toUTCString() exclusively.
242+
243+
Date/Time Component Methods
244+
The remaining methods of the Date type (listed in the following table) deal directly with getting and
245+
setting specific parts of the date value. Note that references to a UTC date mean the date value when
246+
interpreted without a time-zone offset (the date when converted to GMT).
247+
METHOD DESCRIPTION
248+
getTime() Returns the milliseconds representation of the date; same as
249+
valueOf().
250+
setTime(milliseconds) Sets the milliseconds representation of the date, thus changing the entire date.
251+
getFullYear() Returns the four-digit year (2019 instead of just 19).
252+
getUTCFullYear() Returns the four-digit year of the UTC date value.
253+
setFullYear(year) Sets the year of the date. The year must be given with four digits (2019 instead of just 19).
254+
setUTCFullYear(year) Sets the year of the UTC date. The year must be given with four digits (2019 instead of just 19).
255+
getMonth() Returns the month of the date, where 0 represents January and 11 represents December.
256+
getUTCMonth() Returns the month of the UTC date, where 0 represents January and 11 represents December.
257+
setMonth(month) Sets the month of the date, which is any number 0 or greater. Numbers greater than 11 add years.
258+
setUTCMonth(month) Sets the month of the UTC date, which is any number 0 or greater. Numbers greater than 11 add years.
259+
getDate() Returns the day of the month (1 through 31) for the date.
260+
getUTCDate() Returns the day of the month (1 through 31) for the UTC date.
261+
setDate(date) Sets the day of the month for the date. If the date is greater
262+
than the number of days in the month, the month value also
263+
gets increased.
264+
setUTCDate(date) Sets the day of the month for the UTC date. If the date is greater than the number of days in the month, the month value also gets increased.
265+
getDay() Returns the date’s day of the week as a number (where 0 represents Sunday and 6 represents Saturday).
266+
getUTCDay() Returns the UTC date’s day of the week as a number (where 0 represents Sunday and 6 represents Saturday).
267+
getHours() Returns the date’s hours as a number between 0 and 23.
268+
getUTCHours() Returns the UTC date’s hours as a number between 0 and 23.
269+
setHours(hours) Sets the date’s hours. Setting the hours to a number greater than 23 also increments the day of the month.
270+
setUTCHours(hours) Sets the UTC date’s hours. Setting the hours to a number greater than 23 also increments the day of the month.
271+
getMinutes() Returns the date’s minutes as a number between 0 and 59.
272+
getUTCMinutes() Returns the UTC date’s minutes as a number between 0 and 59.
273+
setMinutes(minutes) Sets the date’s minutes. Setting the minutes to a number greater than 59 also increments the hour.
274+
setUTCMinutes(minutes) Sets the UTC date’s minutes. Setting the minutes to a number greater than 59 also increments the hour.
275+
getSeconds() Returns the date’s seconds as a number between 0 and 59.
276+
getUTCSeconds() Returns the UTC date’s seconds as a number between 0 and 59.
277+
setSeconds(seconds) Sets the date’s seconds. Setting the seconds to a number greater than 59 also increments the minutes.
278+
setUTCSeconds(seconds) Sets the UTC date’s seconds. Setting the seconds to a number greater than 59 also increments the minutes.
279+
getMilliseconds() Returns the date’s milliseconds.
280+
getUTCMilliseconds() Returns the UTC date’s milliseconds.
281+
setMilliseconds(milliseconds) Sets the date’s milliseconds.
282+
setUTCMilliseconds(milliseconds) Sets the UTC date’s milliseconds.
283+
getTimezoneOffset() Returns the number of minutes that the local time zone is offset from UTC. For example, Eastern Standard Time returns 300. This value changes when an area goes into Daylight Saving Time. */

0 commit comments

Comments
 (0)