0

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;
5
  • Perhaps you mean Javascript? Retagging. Commented Nov 11, 2010 at 14:39
  • Isn't JavaScript instead of HTML... or simply in which language is written the code you provide ? look a mix of JS/Java Commented Nov 11, 2010 at 14:39
  • no i wanted to use this function in java servlet.So i wanted the java servlet code for this Commented Nov 11, 2010 at 14:40
  • with servlet, for first line of code you would need to do request.getParameter("name of field"); Servlets dont have the option to pick something with id. After that, SimpleDateFormat and Date class would get you going. Commented Nov 11, 2010 at 14:44
  • The DOM access might be a bit tricky from as servlet, why don't you state the goal of the servlet instead? Is it to calculate age based on a http parameter or something else? Commented Nov 11, 2010 at 14:46

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

9 Comments

i m using datepicker and also date format for this.I have implemented this in jsp code and i want to implement the same code in servlet
OK. What stops you from doing this? (note that JSP != JavaScript)
yeah i know that. Let me give u my jsp code and servlet code.
function getAge(id) { getFormattedDate(id); var dob1 = document.getElementById(id).value; var today = new Date(), dob = new Date(dob1), age = new Date(today - dob).getFullYear() - 1970; document.getElementById('age').value = age; }
Here is an Ant file which converts JSP code to Servlet (I havent tried on my own). You should go through some jsp/servlet tutorials. arulraj.net/2010/04/jsp-to-servlet-converter.html
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.