#12- Próximo cumpleaños
Muchos lenguajes de programación cuentan con un módulo para manejar tiempo y fechas. Haz uso de este módulo para crear un programa al que le ingreses tu fecha de nacimiento y te diga cuantos días faltan para tu próximo cumpleaños.
Hecho en Python
from datetime import datetime defnext_birthday(date, now):if date < now: date = date.replace(year=date.year + 1) diff = date - now hours, seconds = divmod(diff.seconds, 60 * 60) minutes, seconds = divmod(seconds, 60) return (diff.days, hours, minutes, seconds) defmain(): print("Next Birthday".center(50)) print("*" * 50) now = datetime.now() whileTrue: try: day = int(input("Day: ")) month = int(input("Month (numeric): ")) converted_date = datetime(day=day, month=month, year=now.year) except: print("There was an error, please try again.") else: break birthday = next_birthday(converted_date, now) print(f"Your next birthday is in {birthday[0]} days, {birthday[1]} hours, {birthday[2]} minutes, {birthday[3]} seconds.") if __name__ == "__main__": main()
PYTHON
from datetime import date defBirthday(birthday): today = date.today() birthday = date(today.year,int(birthday[5:7]),int(birthday[8:10])) if birthday < today: birthday = date(today.year + 1,birthday.month,birthday.day) days_birthday = abs(today-birthday) print('') print (f'{days_birthday.days} days to your birthday') if __name__ == "__main__": print(""" BIRTHDAY in Python -------------------------- """) birthday = input('Birthday date (year-month-day) : ') Birthday(birthday)
Javascript
const month = prompt('Ingresa en NUMERO tu mes de nacimiento: ') const day = prompt('Ingresa tu dia de nacimiento: ') var birthday = newDate(2000, month-1, day) var today = newDate() functioncountdown(birthday, today) { if(today.getMonth() >= month-1) { let nextBday1 = birthday.setFullYear(today.getFullYear()+1) let missingTime1 = nextBday1 - today alert(`Cumples anios hasta el ${today.getFullYear()+1}. Faltan ${Math.floor(missingTime1/(1000*60*60*24))+1} dias para tu cumpleanos`) } else { let nextBday2 = birthday.setFullYear(today.getFullYear()) let missingTime2 = nextBday2 - today alert(`Faltan ${Math.floor(missingTime2/(1000*60*60*24))+1} dias para tu cumpleanos`) } } countdown(birthday, today)
En python:
""" Programa que recibe tu fecha de nacimiento y te dice cuantos días faltan para tu próximo cumpleaños. Program that receives your date of birth and tells you how many days are left until your next birthday. """from datetime import date defget_birthday():whileTrue: birth_day = input('Please insert the day of your birth: ') birth_month = input('Please insert the month of your birth: ') birth_year = input('Please insert the year of your birth: ') try: birthday = date(int(birth_year), int(birth_month), int(birth_day)) except: print('Please insert a valid date.') else: return birthday defdays_next_birthday(birthday): years = date.today().year - birthday.year if (date.today().month, date.today().day) >= (birthday.month, birthday.day): years += 1 next_birthday = date(birthday.year + years, birthday.month, birthday.day) days = (next_birthday - date.today()).days return days, years if __name__ == "__main__": print('DAYS TO YOUR NEXT BIRTHDAY') days_years = days_next_birthday(get_birthday()) days = days_years[0] years = days_years[1] print('There is {} days to your next birthday ({} years).' .format(days, years))
Programa corregido teniendo en cuenta 29 de Febrero y evitando fechas negativas:
""" Programa que recibe tu fecha de nacimiento y te dice cuantos días faltan para tu próximo cumpleaños. Program that receives your date of birth and tells you how many days are left until your next birthday. """from datetime import date defask_birthday(): birth_day = input('Please insert the day of your birth: ') birth_month = input('Please insert the month of your birth: ') birth_year = input('Please insert the year of your birth: ') return birth_day, birth_month, birth_year defget_birthday():whileTrue: birth_list = ask_birthday() try: birthday = date(int(birth_list[2]), int(birth_list[1]), int(birth_list[0])) whilenot (date(1900,1,1) < birthday <= date.today()): print('Please insert a valid date.') birth_list = ask_birthday() birthday = date(int(birth_list[2]), int(birth_list[1]), int(birth_list[0])) except: print('Please insert a valid date.') else: return birthday defdays_next_birthday(birthday): years = date.today().year - birthday.year try: if (date.today().month, date.today().day) >= (birthday.month, birthday.day): years += 1 next_birthday = date(birthday.year + years, birthday.month, birthday.day) days = (next_birthday - date.today()).days return days, years except: years = date.today().year - birthday.year real_years = int(years/4) if (date.today().month, date.today().day) >= (birthday.month, birthday.day): years += 1 next_birthday = date(birthday.year + years + 3, birthday.month, birthday.day) days = (next_birthday - date.today()).days return days, real_years+1if __name__ == "__main__": print('DAYS TO YOUR NEXT BIRTHDAY') days_years = days_next_birthday(get_birthday()) days = days_years[0] years = days_years[1] print('There is {} days to your next birthday ({} years old).' .format(days, years))
Python 😃
from datetime import datetime, timedelta, time, date import calendar fecha1 = datetime.now() dia=int(input('agregue el dia de su cumpleaños: ')) mes=int(input('agregue el mes de su cumpleaños: ')) diactual=fecha1.daymesactual=fecha1.month añoactual=fecha1.year nuevoaño=fecha1.year+1if mes<=mesactual: if dia<=diactual: año=nuevoañoelse: año=añoactualelse: año=añoactualfecha2 = datetime(año, mes, dia, 0, 0, 0) diferencia = fecha2 - fecha1 print("Entre hoy ",fecha1 ,"y el dia de tu cumpleaños ", fecha2, "faltan ", diferencia.days, "días")```
Hola Wilson, como sugerencia, no uses ñ en el codigo
Me costo mucho este reto
constTODAY = new Date(); constONEDAY = 1000 * 60 * 60 * 24; const nextBirthday = (t, day) => { let dayUser = parseInt(prompt('Enter your birthday')); let monthUser = parseInt(prompt('Enter your birthday month')) - 1; let birthday = new Date(t.getFullYear(), monthUser, dayUser); let diff = Math.abs(t - birthday); letresult = Math.floor(diff / day); if (birthday > t) { return (result); } elseif (birthday < t) { returnMath.abs(result - 365); } } console.log(nextBirthday(TODAY, ONEDAY))```
Mi solución en JS:
functionhappyBirthDay(birthDate) { let today = newDate(Date.now()); let bDay = newDate(birthDate); let nextBDay = ""; if (bDay.getMonth() < today.getMonth()) { nextBDay = `${bDay.getMonth() + 1}/${bDay.getDate()}/${today.getFullYear() + 1}`; let daysLeft = Math.floor((newDate(nextBDay).getTime() - today.getTime())/ (60 * 60 * 24 * 1000)) + 1; return"Days left until your birth day:" + daysLeft; }else{ nextBDay = `${bDay.getMonth() + 1}/${bDay.getDate()}/${today.getFullYear()}`; let daysLeft = Math.floor((newDate(nextBDay).getTime() - today.getTime())/ (60 * 60 * 24 * 1000)) + 1; return"Days left until your birth day:" + daysLeft; } }
El módulo datetime de Python no lo conocía. Me da gusto que un reto me pida aprenderlo. 😄
from datetime import date hoy = date.today() if __name__ == "__main__": dia = int(input('\nEscribe tu día de nacimiento: ')) mes = int(input('Escribe tu mes de nacimiento: ')) anio = int(input('Escribe tu año de nacimiento: ')) fecha_nacimiento = date(anio, mes, dia) cumpleanos_anio_actual = date(hoy.year, fecha_nacimiento.month, fecha_nacimiento.day) if cumpleanos_anio_actual > hoy: delta = cumpleanos_anio_actual - hoy else: cumpleanos_anio_siguiente = date(hoy.year + 1, fecha_nacimiento.month, fecha_nacimiento.day) delta = cumpleanos_anio_siguiente - hoy print(f'\n\nFaltan {delta.days} días para tu cumpleaños.')
Próximo cumpleaños en Java ☕️ ☕️
public class DiasSiguienteCumple { public static void main(String[] args) { LocalDate fechaActual =LocalDate.now(); Scanner scanner = new Scanner(System.in);System.out.println("Ingresa tu fecha de nacimiento"); String birthDate = scanner.next(); LocalDate birthDay = LocalDate.parse(birthDate); LocalDate nextBirthday = birthDay.withYear(fechaActual.getYear()); long totalDias = 0;//Si la fecha ya pasó le sumamos un año para sacar la diferenciaif (nextBirthday.isBefore(fechaActual)) { nextBirthday = nextBirthday.plusYears(1); } totalDias = ChronoUnit.DAYS.between(fechaActual, nextBirthday);System.out.println("Faltan " + totalDias + " días para tu siguiente cumpleaños! :)"); } }
Resultado del programa

<let myBirthDay = "Sun Nov 6 2020 "; const getRemainTime = (deadline) => { let now = newDate(), remainTime = (newDate(deadline) - now + 1000) / 1000; remainSeconds = ("0" + Math.floor(remainTime % 60)).slice(-2); remainMinutes = ("0" + Math.floor((remainTime / 60) % 60)).slice(-2); remainHours = ("0" + Math.floor((remainTime / 3600) % 24)).slice(-2); remainDays = Math.floor(remainTime / (3600 * 24)); return { remainTime, remainSeconds, remainMinutes, remainHours, remainDays, }; }; console.log(getRemainTime(myBirthDay)); console.log( `Para mi cumpleaños faltan ${remainDays} días,${remainHours} horas y ${remainMinutes} minutos` ); >
#PlatziCodingChallenge Día 12 - Solución al reto con JavaScript
https://github.com/pahoalapizco/PlatziCodingChallenge/tree/day12
Para utilizarlo desde la temrinal:
nodeday12 next -b=1991-11-21
o bien
nodeday12 next --birthday=1991-11-21
Código

Resuldado

def daysToDate(month, day): today = datetime.now() year = today.yearif (today.month, today.day) < (month, day) else today.year + 1return (datetime(year, month, day) - today).days + 1; day = int ( input("Ingrese el dia: ")) month = int ( input ("Ingrese el mes: ")) total = daysToDate(month, day) print("Faltan: ", total)
aqui esta en c++
#include<iostream>usingnamespacestd; intmain(){ int dia1 = 0; int mes1 = 0; int dia2 = 0; int mes2 = 0; int restantesDias = 0; int restantesMes = 0; cout<<"dime que dia es hoy"<<endl; cin>>dia1; cout<<"dime que mes es hoy"<<endl; cin>>mes1; cout<<"ahora dime el dia de tu cumpleaños"<<endl; cin>>dia2; cout<<"ahora dime el mes de tu cumpleaños"<<endl; cin>>mes2; if(mes1<mes2) { int restantesDias = dia2 - dia1; int restantesMes = mes2 - mes1; cout<<"faltan "<< restantesDias <<"dias y "<<restantesMes<<" meses para tu cumpleaños"<<endl; } elseif(mes1==mes2,dia1 == dia2) { cout << "felicidades, tu cumpleaños es hoy!!!"<<endl; } else { int restantesDias = dia2 - dia1; int restantesMes = (mes2 + 12) - mes1; cout<<"faltan "<< restantesDias <<"dias y "<<restantesMes<<" meses para tu cumpleaños"<<endl; } return0; }
El código de este reto en JS, C y C++.
https://github.com/ceporro/PlatziCodingChallenge
C++
#include<iostream>#include<ctime>usingnamespacestd; intmain(){ struct tm a = {0,0,0,25,6,120}; struct tm b = {0,0,0,9,7,120}; time_t x = mktime(&a); time_t y = mktime(&b); if ( x != (time_t)(-1) && y != (time_t)(-1) ) { double diferencia = difftime(y, x) / (60 * 60 * 24); cout << ctime(&x); cout << ctime(&y); cout << "Quedan " << diferencia << " dias para el siguiente cumple" << endl; } return0; }
Salida

No se si soy yo, pero se me complico esto, no tenía mucha idea del manejo de fechas, buen ejercicio…
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Próximo Cumpleaños</title></head><style> * { margin: 0; } .contenedor { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; } .section { padding: 2rem; } .inputs { display: inherit; align-items: center; } .btn { border: 2px solid black; border-radius: 6px; cursor: pointer; } #contra { padding: 020px; width: 95%; } </style><body><divclass="contenedor"><h1>Calcula cuanto tiempo falta para tu cumpleaños c:</h1><divclass="inputs"><sectionclass="section"> Ingresa tu fecha de nacimiento: <inputid="fecha"placeholder="DD-MM-AAAA"/></section><buttononclick="revisa()"class="btn">Calcula...</button></div><divid="resultado"></div></div><script>functionrevisa(){ let nacimiento = document.getElementById('fecha').value.split('-') let dia = parseInt(nacimiento[0]) let mes = parseInt(nacimiento[1]) let año = parseInt(nacimiento[2]) if (!(dia >= 1 && dia <=31)){ document.getElementById('resultado').innerHTML = `Error, día debe estar entre 1 y 31` } elseif(!(mes >= 1 && mes <= 12)) { document.getElementById('resultado').innerHTML = `Error, mes debe estar entre 1 y 12` } elseif(!(año >= 1920 && año <= (newDate().getYear() + 1899))) { document.getElementById('resultado').innerHTML = `Error, el año debe estar entre 1920 y ${new Date().getYear() + 1899}` } else { const añoActual = newDate().getYear() + 1900const cumpleañosAñoActual = newDate(añoActual, mes - 1, dia) const fechaActual = newDate() let diferencia if (cumpleañosAñoActual.getTime() - fechaActual.getTime() < 0){ cumpleañosAñoActual.setYear(cumpleañosAñoActual.getYear() + 1901) diferencia = cumpleañosAñoActual.getTime() - fechaActual.getTime() } else { diferencia = cumpleañosAñoActual.getTime() - fechaActual.getTime() } let dias = Math.floor(diferencia/(1000*60*60*24)) let horas = Math.floor((diferencia/(1000*60*60*24) - Math.floor(diferencia/(1000*60*60*24)))*24) let minutos = Math.floor((((diferencia/(1000*60*60*24) - Math.floor(diferencia/(1000*60*60*24)))*24) - Math.floor(((diferencia/(1000*60*60*24) - Math.floor(diferencia/(1000*60*60*24)))*24)))*60) document.getElementById('resultado').innerHTML = `Faltan ${dias} dias, con ${horas} horas y ${minutos} minutos para tu cumpleaños!` } } </script></body></html>
Python:

Result:

Logre hacer algo muy básico en python.
from datetime import date defproximo_cumpleaños(): hoy = date.today() print(hoy) fecha_cumpleaños = date(2020, 11, 18) dias_faltantes = fecha_cumpleaños - hoy return print(f'Faltan {dias_faltantes} dias para tu cumpleaños.') if __name__ == "__main__": proximo_cumpleaños()
const calc_birthday_days_left = ({ month, day }) => { constnow = newDate(); constyear = now.getFullYear(); const curr_month = now.getMonth() + 1; const to_days = 1 / (1000 * 60 * 60 * 24); const add_year = curr_month < month?0:1 return Math.ceil((newDate(year + add_year, month - 1, day) - newDate()) * to_days) + 1; } console.log(calc_birthday_days_left({ month: 3, day: 12 })) console.log(calc_birthday_days_left({ month: 10, day: 12 }))
Java
import java.util.*; import javax.swing.JOptionPane; public class Main { public static void main(String[] args) throws Exception { Calendar fecha = new GregorianCalendar();int diaAño= fecha.get(Calendar.DAY_OF_YEAR);int mesUser= Integer.parseInt(JOptionPane.showInputDialog("Dame tu mes de nacimiento en número"));int diaUser= Integer.parseInt(JOptionPane.showInputDialog("Dame tu dia de mes nacimiento")); Calendar nacimiento= new GregorianCalendar(2020, (mesUser-1), diaUser);int diaAñoUser=nacimiento.get(Calendar.DAY_OF_YEAR);int cumpleaños;if(diaAño<=diaAñoUser){ cumpleaños=Math.abs(diaAño-diaAñoUser); }else{ int faltante=365-diaAño; cumpleaños=diaAñoUser+faltante; } System.out.println("faltan "+cumpleaños+" dias para tu cumpleaños"); } }
Próximo cumpleaños en JS
Incluí también en calculo de la edad actual.
var fechaCumpleños = "1990/01/01"//Digite fecha de nacimiento en formato yyyy/mm/ddvar ahora = newDate(Date.now()); var parseF = newDate(fechaCumpleños) var mes = (parseF.getMonth()+1); var dia = parseF.getDate(); var año_act = ahora.getFullYear(); var fechaFin = newDate(año_act + '-' + mes + '-' + dia) const MILISEG_DIA = 1000*60*60*24const MILISEG_AÑO = 1000*60*60*24*30.5*12console.log(`Para su próximo cumpleaños faltan ${diasParaCumpleaños(fechaFin,ahora).toFixed(1)} dias`) console.log(`Actualmente tienes ${Math.floor(edad(parseF,ahora))} años de edad.`) functiondiasParaCumpleaños(fechaFin,ahora){ if(fechaFin.getTime() < ahora.getTime()){ año_act += 1 fechaFin = newDate(año_act + '-' + mes + '-' + dia) } var diasDif = fechaFin.getTime() - ahora.getTime(); return diasDif/MILISEG_DIA; } functionedad(parseF,ahora){ var e = (ahora.getTime() - parseF.getTime()) ; return e/MILISEG_AÑO; }
Resultados:
1990/01/01
Para su próximo cumpleaños faltan 164.1 dias
Actualmente tienes 30 años de edad.
1995/05/30
Para su próximo cumpleaños faltan 313.1 dias
Actualmente tienes 25 años de edad.
1983/09/01
Para su próximo cumpleaños faltan 42.1 dias
Actualmente tienes 36 años de edad.
Js
console.clear(); let u = prompt('Tell me your birthday\r\Month/Day'); const dMs = 1000 * 60 * 60 * 24; const d = newDate(); const yToD = (a) => { const yI = newDate(a.getFullYear(),0,0); returnMath.floor((a.getTime() - yI) / dMs); } const t = (up) => { let ub = up.split('/'); let c = yToD(newDate()); if (parseInt(ub[0]) < d.getMonth()) { let un = yToD(newDate((d.getFullYear() + 1),(parseInt(ub[0])-1),parseInt(ub[1]))); return`Still ${ (un + (365 - c)) + 1 } days to your birthday`; } else { let uc = yToD(newDate(d.getFullYear(),(parseInt(ub[0])-1),parseInt(ub[1]))); return`Still ${ ( uc - c ) + 1} days to your birthday`; } } alert(t(u));
Próximo cumpleaños hecho en JavaScript:
//Proximo cumpleaños en JavaScriptconst MILISECONDS_PER_DAY = 1000 * 60 * 60 * 24functiondaysTillBirthday(birthDay, birthMonth) { let today = newDate() today = newDate(today.getFullYear(), today.getMonth(), today.getDate()) let nextBirthday = newDate(today.getFullYear(), birthMonth, birthDay) let timeLeft = nextBirthday.getTime() - today.getTime() if(timeLeft < 0){ nextBirthday = newDate(today.getFullYear() + 1, birthMonth, birthDay) timeLeft = nextBirthday.getTime() - today.getTime() } returnMath.floor(timeLeft / MILISECONDS_PER_DAY) } functionnumeroMes(strMes) { switch(strMes){ case'enero': return0case'febrero': return1case'marzo': return2case'abril': return3case'mayo': return4case'junio': return5case'julio': return6case'agosto': return7case'septiembre': return8case'octubre': return9case'noviembre': return10case'diciembre': return11default: returnNaN } } //Pruebalet diaNacimiento = parseInt(prompt('Introduzca su día de nacimiento')) let mesNacimiento = numeroMes(prompt('Introduzca su mes de nacimiento').toLowerCase()) //Convierte fecha de texto a númerolet diasRestantes = daysTillBirthday(diaNacimiento, mesNacimiento) alert(diasRestantes == 0 ? `Feliz cumpleaños` : `Faltan ${diasRestantes} día(s) para tu cumpleaños`)
Python
import time from datetime import date defmain(): day = int(input('Digite el dia de nacimiento')) month = int(input('Digite el mes de nacimiento')) today = date.today() today == date.fromtimestamp(time.time()) birthday = date(today.year, month, day) if birthday < today: birthday = birthday.replace(year=today.year+1) days_left = abs(birthday - today) print(days_left.days) if __name__ == '__main__': main()
En Python, además de lo del cumpleaños también calcula cuantos días llevas de vida.
from datetime import date defcalcTime(day, month):try: today = date.today() userConverted = date(month=month, day=day, year=(today.year + 1)) diferencia = (userConverted - today) diferenciaSin = diferencia.days return diferenciaSin except: print('Ingresa una fecha valida') defcalcLive(day, month): year = int(input('Y en que año naciste? ')) today = date.today() userConverted = date(month=month, day=day, year=year) if userConverted < today: diferencia = today - userConverted diferenciaSin = diferencia.days print(f'llevas {diferenciaSin} dias de vida') else: print('Elige un año valido') if __name__ == "__main__": day = int(input('Que dia cumples ')) month = int(input('En que mes cumples ')) respuesta = calcTime(day, month) if respuesta == None: Noneelse: print(f'Quedan {respuesta} dias para tu Cumpleaños') calcLive(day, month) ```
python
from datetime import date from datetime import datetime defbirthday(your_bday): your_bday = your_bday.split("-") year = datetime.now().year your_bday = date(year, int(your_bday[0]), int(your_bday[1])) today = date.today() days = your_bday - today print(days.days,"dias para tu cumpleños") if __name__ == "__main__": your_bday = input("Ingresa tu fecha de cumpleaños: mes-dia: ") birthday(your_bday)
Reto 12: Próximo cumpleaños
Repositorio del reto: PlatziCodingChallengeRepo
GitHub pages: PlatziCodingChallengePages
function getDays(dateBirthDay, dateNow) { let days; let edad = dateBirthDay.getFullYear(); dateBirthDay.setFullYear(dateNow.getFullYear()); let msPerDay = 24 * 60 * 60 * 1000;if(dateNow.getTime() >= dateBirthDay.getTime()) { //dateNow.setFullYear(dateNow.getFullYear()+1); dateBirthDay.setFullYear(dateNow.getFullYear()+1); } edad = dateNow.getFullYear() - edad; days = (dateBirthDay.getTime() -dateNow.getTime()) / msPerDay; days = Math.round(days);return { days, edad }; }
En Python, me costó un poco pero ya está mi solución:}
from datetime import date from datetime import datetime from datetime import timedelta today = date.today() defcalcula_dias_faltantes(fecha): dias_faltantes = fecha - today print('Faltan ', dias_faltantes, 'dias para tu próximo cumpelaños.') defrun(): fecha = str(input('Ingresa la fecha de tu cumpleaños. yyyy-mm-dd: ')) fecha = date.fromisoformat(fecha) new_fecha = date(today.year, fecha.month, fecha.day) calcula_dias_faltantes(new_fecha) if __name__ == '__main__': run()```
Listo 😎👍🏻 (Hecho con Python)
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><labelfor="dia">Dia</label><inputtype="text"id="dia"name="value"><labelfor="mes">Mes</label><inputtype="text"id="mes"name="value"><buttontype="button"onclick="HandleClick()">Calcular</button><h1id="valor"></h1><script>functionHandleClick(){ const milisegundos_dia=1000 * 60 * 60 * 24; let fecha=newDate(); let hoy=newDate(fecha.getFullYear(), fecha.getMonth(), fecha.getDate()); let $mes=document.getElementById("mes").value; $mes=convertidor($mes); let $dia=document.getElementById("dia").value; let $valor=document.getElementById("valor"); let cumpleaños=newDate(hoy.getFullYear(), $mes, $dia); let tiempo= cumpleaños.getTime() - hoy.getTime(); if(tiempo<0){ cumpleaños= newDate(hoy.getFullYear()+1, $mes, $dia); tiempo= cumpleaños.getTime() - hoy.getTime(); } let resultado = Math.floor(tiempo/milisegundos_dia); $valor.innerHTML=`${resultado}`; } functionconvertidor(mes){ let int=parseInt(mes); int=int-1; let str= int.toString(); return str; } </script></body></html>