fork(1) download
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. #include <chrono>
  5. using namespace std;
  6.  
  7. struct AgeDetail {
  8. int years;
  9. int months;
  10. int days;
  11. };
  12.  
  13. AgeDetail calculateAge(int birthYear, int birthMonth, int birthDay) {
  14. using namespace chrono;
  15.  
  16. // Ambil tanggal sekarang
  17. auto today = system_clock::now();
  18. time_t t = system_clock::to_time_t(today);
  19. tm now = *localtime(&t);
  20.  
  21. int yearNow = now.tm_year + 1900;
  22. int monthNow = now.tm_mon + 1;
  23. int dayNow = now.tm_mday;
  24.  
  25. AgeDetail age{};
  26. age.years = yearNow - birthYear;
  27. age.months = monthNow - birthMonth;
  28. age.days = dayNow - birthDay;
  29.  
  30. if (age.days < 0) {
  31. age.months--;
  32. static int daysInMonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
  33. int prevMonth = (monthNow - 2 + 12) % 12;
  34. int yearOfPrevMonth = yearNow;
  35. if (monthNow == 1) yearOfPrevMonth--;
  36. // cek kabisat
  37. if (prevMonth == 1 && ((yearOfPrevMonth % 4 == 0 && yearOfPrevMonth % 100 != 0) || (yearOfPrevMonth % 400 == 0))) {
  38. daysInMonth[1] = 29;
  39. } else {
  40. daysInMonth[1] = 28;
  41. }
  42. age.days += daysInMonth[prevMonth];
  43. }
  44.  
  45. if (age.months < 0) {
  46. age.years--;
  47. age.months += 12;
  48. }
  49.  
  50. return age;
  51. }
  52.  
  53. int main() {
  54. string fullName;
  55. int birthYear, birthMonth, birthDay;
  56.  
  57. cout << "Nama: ";
  58. getline(cin, fullName);
  59.  
  60. cout << "Tanggal lahir (YYYY MM DD): ";
  61. cin >> birthYear >> birthMonth >> birthDay;
  62.  
  63. string firstName, middleName, lastName;
  64. stringstream ss(fullName);
  65. ss >> firstName >> middleName >> lastName;
  66.  
  67. AgeDetail age = calculateAge(birthYear, birthMonth, birthDay);
  68.  
  69. if (middleName.empty()) {
  70. cout << "Woi, " << firstName << ", lu udah "
  71. << age.years << " tahun, "
  72. << age.months << " bulan, "
  73. << age.days << " hari." << endl;
  74. } else {
  75. cout << "Woi, " << middleName << ", lu udah "
  76. << age.years << " tahun, "
  77. << age.months << " bulan, "
  78. << age.days << " hari." << endl;
  79. }
  80.  
  81. return 0;
  82. }
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
Nama: Tanggal lahir (YYYY MM DD): Woi, , lu udah 2025 tahun, 8 bulan, 9 hari.