使用Date Util在java中显示出生日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2923227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Displaying Date Of Birth in java by using Date Util
提问by via_point
I'm testing a Person 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:
我正在测试一个 Person 类,该类对具有姓名、地址和出生日期的人进行建模。如何设置 dob(出生日期)?
这是我的 Person 类:
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
采纳答案by Powerlord
If you have the fields as numbers, you can use a Calendar object to create a Date.
如果您将字段作为数字,则可以使用 Calendar 对象来创建日期。
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));
回答by jwismar
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).
您需要传入一个类似日期的对象,或者一个将被解析的字符串。看起来您正在传入一个整数表达式(计算结果为 0)。