如何在不使用已弃用方法的情况下从 Date 对象获取年份?
How can I get the year from a Date object without using deprecated methods?
我接到了一项任务,我需要为一家汽车租赁公司创建一组接口和 classes。我正忙于实施必须符合以下规范的 LicenceNumber class:
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 class 的以下实现:
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 对象获取年份吗?[=12=]
先谢谢了。
试试这个
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year = localDate.getYear();
这里是修复
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
System.out.println(calendar.get(Calendar.YEAR));
用您想要获取年份的日期替换新日期。
看看 https://docs.oracle.com/javase/8/docs/api/java/text/DateFormat.html 和相关的 类。这可以从给定的 'Date'.
中生成仅包含 "year" 字段的字符串
我可以想到三种从 Date
对象获取年份的方法,但要避免使用已弃用的方法。其中两种方法使用其他对象(Calendar
和 SimpleDateFormat
),第三种方法解析 Date
对象的 .toString()
(并且该方法不是 已弃用)。 .toString()
可能是特定于语言环境的,在其他语言环境中该方法可能存在问题,但我将假设(著名的遗言)年份始终是唯一的 4 位数字序列。人们还可以了解特定的语言环境并使用其他解析方法。例如,标准 US/English 将年份放在末尾(例如 "Tue Mar 04 19:20:17 MST 2014"),可以在 .toString()
.
上使用 .lastIndexOf(" ")
/**
* Obtains the year by converting the date .toString() and
* finding the year by a regular expression; works by assuming that
* no matter what the locale, only the year will have 4 digits
*/
public static String getYearByRegEx(Date dte) throws IllegalArgumentException
{
String year = "";
if (dte == null) {
throw new IllegalArgumentException("Null date!");
}
// match only a 4 digit year
Pattern yearPat = Pattern.compile("^.*([\d]{4}).*$");
// convert the date to its String representation; could pass
// this directly, but I prefer the intermediary variable for
// potential debugging
String localDate = dte.toString();
// obtain a matcher, and then see if we have the expected value
Matcher match = yearPat.matcher(localDate);
if (match.matches() && match.groupCount() == 1) {
year = match.group(1);
}
return year;
}
/**
* Constructs a Calendar object, and then obtains the year
* by using the Calendar.get(...) method for the year.
*/
public static String getYearFromCalendar(Date dte) throws IllegalArgumentException
{
String year = "";
if (dte == null) {
throw new IllegalArgumentException("Null date!");
}
// get a Calendar
Calendar cal = Calendar.getInstance();
// set the Calendar to the specific date; the reason why
// Calendar is deprecated is this mutability
cal.setTime(dte);
// get the year using the .get method, and convert to a String
year = String.valueOf(cal.get(Calendar.YEAR));
return year;
}
/**
* Uses the SimpleDateFormat with a format for only a year.
*/
public static String getYearByFormatting(Date dte)
throws IllegalArgumentException
{
String year = "";
if (dte == null) {
throw new IllegalArgumentException("Null date!");
}
// set a format only for the year
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
// format the date; the result is the year
year = sdf.format(dte);
return year;
}
public static void main(String[] args)
{
Calendar cal = Calendar.getInstance();
cal.set(2014,
Calendar.MARCH,
04);
Date dte = cal.getTime();
System.out.println("byRegex: "+ getYearByRegEx(dte));
System.out.println("from Calendar: "+ getYearFromCalendar(dte));
System.out.println("from format: " + getYearByFormatting(dte));
}
所有三种方法都return基于测试输入的预期输出。
我接到了一项任务,我需要为一家汽车租赁公司创建一组接口和 classes。我正忙于实施必须符合以下规范的 LicenceNumber class:
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 class 的以下实现:
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 对象获取年份吗?[=12=]
先谢谢了。
试试这个
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year = localDate.getYear();
这里是修复
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
System.out.println(calendar.get(Calendar.YEAR));
用您想要获取年份的日期替换新日期。
看看 https://docs.oracle.com/javase/8/docs/api/java/text/DateFormat.html 和相关的 类。这可以从给定的 'Date'.
中生成仅包含 "year" 字段的字符串我可以想到三种从 Date
对象获取年份的方法,但要避免使用已弃用的方法。其中两种方法使用其他对象(Calendar
和 SimpleDateFormat
),第三种方法解析 Date
对象的 .toString()
(并且该方法不是 已弃用)。 .toString()
可能是特定于语言环境的,在其他语言环境中该方法可能存在问题,但我将假设(著名的遗言)年份始终是唯一的 4 位数字序列。人们还可以了解特定的语言环境并使用其他解析方法。例如,标准 US/English 将年份放在末尾(例如 "Tue Mar 04 19:20:17 MST 2014"),可以在 .toString()
.
.lastIndexOf(" ")
/**
* Obtains the year by converting the date .toString() and
* finding the year by a regular expression; works by assuming that
* no matter what the locale, only the year will have 4 digits
*/
public static String getYearByRegEx(Date dte) throws IllegalArgumentException
{
String year = "";
if (dte == null) {
throw new IllegalArgumentException("Null date!");
}
// match only a 4 digit year
Pattern yearPat = Pattern.compile("^.*([\d]{4}).*$");
// convert the date to its String representation; could pass
// this directly, but I prefer the intermediary variable for
// potential debugging
String localDate = dte.toString();
// obtain a matcher, and then see if we have the expected value
Matcher match = yearPat.matcher(localDate);
if (match.matches() && match.groupCount() == 1) {
year = match.group(1);
}
return year;
}
/**
* Constructs a Calendar object, and then obtains the year
* by using the Calendar.get(...) method for the year.
*/
public static String getYearFromCalendar(Date dte) throws IllegalArgumentException
{
String year = "";
if (dte == null) {
throw new IllegalArgumentException("Null date!");
}
// get a Calendar
Calendar cal = Calendar.getInstance();
// set the Calendar to the specific date; the reason why
// Calendar is deprecated is this mutability
cal.setTime(dte);
// get the year using the .get method, and convert to a String
year = String.valueOf(cal.get(Calendar.YEAR));
return year;
}
/**
* Uses the SimpleDateFormat with a format for only a year.
*/
public static String getYearByFormatting(Date dte)
throws IllegalArgumentException
{
String year = "";
if (dte == null) {
throw new IllegalArgumentException("Null date!");
}
// set a format only for the year
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
// format the date; the result is the year
year = sdf.format(dte);
return year;
}
public static void main(String[] args)
{
Calendar cal = Calendar.getInstance();
cal.set(2014,
Calendar.MARCH,
04);
Date dte = cal.getTime();
System.out.println("byRegex: "+ getYearByRegEx(dte));
System.out.println("from Calendar: "+ getYearFromCalendar(dte));
System.out.println("from format: " + getYearByFormatting(dte));
}
所有三种方法都return基于测试输入的预期输出。