java - 获取昨天 - 日期类型的方法 getDate() 已弃用

标签 java date

我试图获取昨天的日期。所以我写了下一个函数:

public  String getYestrday() {
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date date = new Date();
    return dateFormat.format(date.getDate() - 1);
}

但它给了我下一个警告:

The method getDate() from the type Date is deprecated

但它不起作用。

感谢您的帮助。

最佳答案

Date#getDate()是 JDK 1.1 之后弃用的方法。你应该使用 Calendar类而不是操纵日期。

来自 API :

Prior to JDK 1.1, the class Date had two additional functions. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed the formatting and parsing of date strings. Unfortunately, the API for these functions was not amenable to internationalization. As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated.

在 API 中使用 Date#getDate() 也清楚地记录了这一点使用 Calendar#get(Calendar.DATE);

Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.DAY_OF_MONTH)

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return dateFormat.format(cal.getTime());

关于java - 获取昨天 - 日期类型的方法 getDate() 已弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14938253/

相关文章:

Java日期解析

javascript - 夏令时开始时的无效时间

Java - 我的霍夫曼解压拒绝解压非文本文件(返回空文件)

javascript - 如何从包含 AM/PM 的日期字符串创建日期对象?

ruby-on-rails - 如何将字符串转换为 ActiveSupport::TimeWithZone?

java - 为什么在带有 Java 8 日期的 Jackson 的 ObjectMapper 中使用 dateFormat 时不从 JSON 中排除毫秒?

java - @OneToOne 与 JPA 的关系

java - 单击 JButton 时将不同的图像绘制到 JButton

java - 如何使用 Spring Social 从 Facebook 注销

java - 按钮放置和位置不起作用