我接到一项任务,需要为一家汽车租赁公司创建一组接口(interface)和类。我正忙于实现一个必须符合以下规范的 LicenseNumber 类:
The licence number has three components. The first component is the concatenation of the initial of the first name of the driver with the initial of the last name of the driver. The second component is the year of issue of the licence. The third component is an arbitrary serial number. For example, the string representation of the licence number for a licence issued to Mark Smith in 1990 would have the form, MS-1990-10, where the 10 is a serial number that, with the initials and year, guarantees the uniqueness of the licence number as a whole.
You should use the java.util.Date class to represent dates. However, you must not use deprecated methods of the Date class. So, for example, in your test classes use java.util.Calendar to construct dates of birth and dates of issue of licences. You can assume default time zone and locale. (Note, there are now better classes available in the java.time package which was introduced in Java 1.8 but it will be good experience to work with classes which are written less well).
到目前为止,我已经获得了 LicenceNumber 类的以下实现:
import java.util.Calendar;
import java.util.Date;
public class LicenceNumber {
private String licenceNo;
public LicenceNumber(Name driverName, Date issueDate){
setLicenceNo(driverName, issueDate);
}
public String getLicenceNo() {
return licenceNo;
}
public void setLicenceNo(Name driverName, Date issueDate) {
String initials;
initials = driverName.getForename().substring(0, 1) + driverName.getSurname().substring(0,1);
System.out.println(initials);
int issueYear = issueDate.getYear(); //Deprecated
}
}
我希望能够从 IssueDate 中仅获取年份,但我能弄清楚如何做到这一点的唯一方法是使用已弃用的方法 getYear()。这显然违反了标准,因此任何人都可以阐明如何在不使用已弃用的方法的情况下从 Date 对象获取 Year 吗?
先谢谢了。
最佳答案
试试这个
日期日期 = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
intyear = localDate.getYear();
这是修复
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
System.out.println(calendar.get(Calendar.YEAR));
将新日期替换为您想要获取年份的日期。
关于java - 如何在不使用已弃用的方法的情况下从 Date 对象获取年份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37124269/