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;
-
Perhaps you mean Javascript? Retagging.Justin Garrick– Justin Garrick2010年11月11日 14:39:07 +00:00Commented 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/JavaAlois Cochard– Alois Cochard2010年11月11日 14:39:32 +00:00Commented Nov 11, 2010 at 14:39
-
no i wanted to use this function in java servlet.So i wanted the java servlet code for thisyopirates– yopirates2010年11月11日 14:40:01 +00:00Commented 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.t0mcat– t0mcat2010年11月11日 14:44:38 +00:00Commented 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?Mikko Wilkman– Mikko Wilkman2010年11月11日 14:46:14 +00:00Commented Nov 11, 2010 at 14:46
1 Answer 1
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
answered Nov 11, 2010 at 14:44
BalusC
1.1m377 gold badges3.7k silver badges3.6k bronze badges
Sign up to request clarification or add additional context in comments.
9 Comments
yopirates
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
BalusC
OK. What stops you from doing this? (note that JSP != JavaScript)
yopirates
yeah i know that. Let me give u my jsp code and servlet code.
yopirates
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; }
t0mcat
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
|
default