Displaying Date Of Birth in java by using Date Util
I'm testing a Perso开发者_如何学Gon class that models a person with name, address and date of birth. How do I set dob (date of birth)?
Here is my Person class:import java.util.Date;
public class Person{
private String name;
private String address;
private Date dob;
public Person( ){
name = null;
address = null;
dob = null;
}
public Person(String nameValue, String newAddress, Date newDob){
name = nameValue;
address = newAddress;
dob = newDob;
}
public String getName(){
return name;
}
public void setName(String nameValue){
name = nameValue;
}
public int getAddress(){
return address;
}
public void setAddress(String newAddress){
address = newAddress;
}
public int getDateOfBirth(){
return dob;
}
public void setDateOfBirth(Date newDob){
dob = newDob;
}
public void print(){
System.out.println("Name: " + name);
System.out.println ("Date Of Birth: " + dob);
System.out.println ("Address: " + address);
}
}
PersonTester{
Person a = new Person();
a.setName("John Smith");
a.setDateOfBirth (01/08/1985);??? - doesn't work
If you have the fields as numbers, you can use a Calendar object to create a Date.
import java.util.Calendar;
// class definition here, etc...
Calendar cal = Calendar.getInstance();
cal.set(1985, 1, 8); // Assumes MM/dd/yyyy
//cal.set(1985, 8, 1); // Assumes dd/MM/yyyy
// cal.getTime() returns a Date object
a.setDateOfBirth(cal.getTime());
If it comes as text in the format you stated earlier, you can instead do this:
import java.text.SimpleDateFormat;
String dateString = "01/08/1985";
// class definition here, etc...
formatter = new SimpleDateFormat("MM/dd/yyyy");
// formatter = new SimpleDateFormat("dd/MM/yyyy");
a.setDateOfBirth(formatter.parse(dateString));
Check this tutorial on how to parse a string as a date
You need to either pass in a date-like object, or a string that will be parsed. It looks like you're passing in an integer expression (that evaluates to 0).
精彩评论