如何从date对象获取年份而不使用不推荐的方法?

lbsnaicq  于 2021-07-03  发布在  Java
关注(0)|答案(3)|浏览(288)

我接到一个任务,需要为一家汽车租赁公司创建一组接口和类。我正忙于实现必须符合以下规范的licenseNumber类:
许可证号码有三个组成部分。第一个组件是驱动程序名的首字母与驱动程序姓的首字母的串联。第二个组成部分是颁发许可证的年份。第三个组件是任意序列号。例如,1990年发给马克·史密斯的许可证的许可证号码的字符串表示形式为ms-1990-10,其中10是一个序列号,加上缩写和年份,可以保证整个许可证号码的唯一性。
应该使用java.util.date类来表示日期。但是,不能使用date类的已弃用方法。因此,例如,在测试类中,使用java.util.calendar来构造出生日期和颁发许可证的日期。可以假定为默认时区和区域设置(注意,现在java.time包中提供了更好的类,该包是在Java1.8中引入的,但是使用编写得不太好的类将是一种很好的体验。
到目前为止,我已经为licenseNumber类实现了以下功能:

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对象获取年份而不使用不推荐的方法吗?
谢谢你。

jucafojl

jucafojl1#

看一看https://docs.oracle.com/javase/8/docs/api/java/text/dateformat.html 以及相关的课程。这可以生成一个字符串,其中只包含给定“date”中的“year”字段。

gj3fmq9x

gj3fmq9x2#

试试这个
日期=新日期();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));

将新日期替换为您希望从中获取年份的日期。

piok6c0g

piok6c0g3#

我可以想出三种方法从一个 Date 对象,但避免使用不推荐的方法。其中两种方法使用其他对象( Calendar 以及 SimpleDateFormat ),第三个解析 .toString()Date 对象(并且该方法未被弃用)。这个 .toString() 可能是特定于语言环境的,在其他语言环境中这种方法可能会有问题,但我将假设(著名的遗言)年份始终是4位数字的唯一序列。还可以理解特定的语言环境并使用其他解析方法。例如,标准美式英语将年份放在末尾(例如,“tue mar 04 19:20:17 mst 2014”),可以使用 .lastIndexOf(" ").toString() .

/**
 * 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));
}

这三种方法都返回基于测试输入的预期输出。

相关问题