- Get link
- X
- Other Apps
package com.ahmad.apandi;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class Main {
public static void main(String[] args) throws Exception {
// write your code here
int tahun = 0, bulan = 0, tanggal = 0;
String tanggalKu;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Masukan tahun lahir : ");
try{
tahun = Integer.parseInt(br.readLine());
}catch(NumberFormatException nfe){
System.err.println("Masukan Hanya Angkat!");
}
System.out.print("Masukan Bulan Lair: ");
try{
bulan = Integer.parseInt(br.readLine());
}catch(NumberFormatException nfe){
System.err.println("Masukan Hanya Angkat!!");
}
System.out.print("Masukan Tanggal Lair: ");
try{
tanggal = Integer.parseInt(br.readLine());
}catch(NumberFormatException nfe){
System.err.println("Masukan Hanya Angkat!");
}
tanggalKu=String.valueOf(tanggal)+"-"+String.valueOf(bulan)+"-"+String.valueOf(tahun);
String umurKu=Main.getUmurKu(tanggalKu);
System.out.println(umurKu);
}
public static String getUmurKu(String tglLahir) throws Exception {
SimpleDateFormat formatter= new SimpleDateFormat("dd-MM-yyyy");
String EFFDATE = tglLahir;
Date startdate = formatter.parse(EFFDATE);
Date enddate = new Date();
Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startdate);
Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(enddate);
if(startCalendar.after(endCalendar)){
return "Tanggal lahir tidak boleh hari yang akan datang";
}
int monthCount = 0;
int firstDayInFirstMonth = startCalendar.get(Calendar.DAY_OF_MONTH);
startCalendar.set(Calendar.DAY_OF_MONTH, 1);
endCalendar.add(Calendar.DAY_OF_YEAR, -firstDayInFirstMonth+1);
while (!startCalendar.after(endCalendar)) {
startCalendar.add(Calendar.MONTH, 1);
++monthCount;
}
startCalendar.add(Calendar.MONTH, -1); --monthCount;
int remainingDays = 0;
while (!startCalendar.after(endCalendar)) {
startCalendar.add(Calendar.DAY_OF_YEAR, 1);
++remainingDays;
}
startCalendar.add(Calendar.DAY_OF_YEAR, -1);
--remainingDays;
int lastMonthMaxDays = endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);
if (remainingDays >= lastMonthMaxDays) {
++monthCount;
remainingDays -= lastMonthMaxDays;
}
int diffMonth = monthCount;
int diffDay = remainingDays;
int diffYear=0;
if(diffMonth>12){
diffYear=diffMonth/12;
diffMonth=diffMonth%12;
}
return diffYear+" Tahun "+diffMonth+" Bulan "+ diffDay+" Hari";
}
}
Comments