|
| 1 | +const currentDate: Date = new Date(); |
| 2 | +const birthdate: Date = new Date('2001-10-21T08:30:00'); |
| 3 | + |
| 4 | +function calculateAge(currentDate: Date, birthdate: Date): number { |
| 5 | + let age: number = currentDate.getFullYear() - birthdate.getFullYear(); |
| 6 | + const month: number = currentDate.getMonth() - birthdate.getMonth(); |
| 7 | + |
| 8 | + if (month < 0 || (month === 0 && currentDate.getDate() < birthdate.getDate())) { |
| 9 | + age--; |
| 10 | + } |
| 11 | + |
| 12 | + return age; |
| 13 | +} |
| 14 | + |
| 15 | +const age: number = calculateAge(currentDate, birthdate); |
| 16 | +console.log(`${age} years have passed since the date of birth`); |
| 17 | + |
| 18 | +// ** Extra Exercise ** // |
| 19 | +const dayMonthYear: string = birthdate.toLocaleDateString('es-ES'); |
| 20 | + |
| 21 | +const hourMinuteSecond: string = birthdate.toLocaleTimeString('es-ES'); |
| 22 | + |
| 23 | +const startYear: Date = new Date(birthdate.getFullYear(), 0, 0); |
| 24 | +const difference: number = birthdate.getTime() - startYear.getTime(); |
| 25 | +const oneDay: number = 1000 * 60 * 60 * 24; |
| 26 | +const dayOfTheYear: number = Math.floor(difference / oneDay); |
| 27 | + |
| 28 | +const dayOfTheWeek: string = birthdate.toLocaleDateString('es-ES', { weekday: 'long' }); |
| 29 | + |
| 30 | +const nameMonth: string = birthdate.toLocaleDateString('es-ES', { month: 'long' }); |
| 31 | + |
| 32 | +const longDate: string = birthdate.toLocaleDateString('es-ES', { year: 'numeric', month: 'long', day: 'numeric' }); |
| 33 | + |
| 34 | +const formatISO: string = birthdate.toISOString(); |
| 35 | + |
| 36 | +const formatUTC: string = birthdate.toUTCString(); |
| 37 | + |
| 38 | +const timeUnix: number = birthdate.getTime(); |
| 39 | + |
| 40 | +const abbreviatedDate: string = birthdate.toLocaleDateString('es-ES', { weekday: 'short', month: 'short', day: 'numeric' }); |
| 41 | + |
| 42 | +console.log('Day, month and year:', dayMonthYear); |
| 43 | +console.log('Hour, minute and second:', hourMinuteSecond); |
| 44 | +console.log('Day of the year:', dayOfTheYear); |
| 45 | +console.log('Day of the week:', dayOfTheWeek); |
| 46 | +console.log('Name of the month:', nameMonth); |
| 47 | +console.log('Long date:', longDate); |
| 48 | +console.log('Format ISO:', formatISO); |
| 49 | +console.log('Format UTC:', formatUTC); |
| 50 | +console.log('Time in milliseconds since 1970:', timeUnix); |
| 51 | +console.log('Abbreviated date:', abbreviatedDate); |
0 commit comments