简体   繁体   中英

Converting JavaScript function to Java

I want to change this code from JavaScript to Java servlet. Can anyone guide me in finding the solution?

 var dob1 =  document.getElementById(id).value;
 var today = new Date(),
 dob = new Date(dob1),
 age = new Date(today - dob).getFullYear() - 1970;

Use the Calendar API.

String dobString = "1978-03-26";
Date dobDate = new SimpleDateFormat("yyyy-MM-dd").parse(dobString);

Calendar dobCalendar = Calendar.getInstance();
dobCalendar.setTime(dobDate);
Calendar today = Calendar.getInstance();
int age = -1;

while (today.after(dobCalendar)) {
    age++;
    today.add(Calendar.YEAR, -1);
}

System.out.println(age); // 32

Since the Calendar API is horrible, I'd suggest JodaTime instead.

String dobString = "1978-03-26";
DateTime dobDate = DateTimeFormat.forPattern("yyyy-MM-dd").parseDateTime(dobString);
DateTime today = new DateTime();
int age = Years.yearsBetween(dobDate, today).getYears();
System.out.println(age); // 32

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM