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.getElementByI开发者_运维问答d(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
精彩评论