获取昨天 – 不推荐使用Date类型的方法getDate()

我试着得到昨天的日期。 所以我写下一个函数:

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

在JDK 1.1之前,Date类有两个附加function。 它允许将日期解释为年,月,日,小时,分钟和秒值。 它还允许格式化和解析日期字符串。 不幸的是,这些function的API不适合国际化。 从JDK 1.1开始,Calendar类应该用于在日期和时间字段之间进行转换,而DateFormat类应该用于格式化和解析日期字符串。 不推荐使用Date中的相应方法。

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

已过时。 从JDK 1.1版开始,由Calendar.get(Calendar.DAY_OF_MONTH)取代

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

使用java.util.Calendar来完成它。 或者尝试JODA 。

避免使用java.util.Date和.Calendar

接受的答案是正确的。 但是,java.util.Date和.Calendar类非常麻烦。 避免他们。 使用Joda-Time或新的java.time包 (在Java 8中)。

从格式化中分离日期时间操作

此外,问题中的代码将日期时间工作与格式混合。 将这些任务分开,使代码清晰,测试/调试更容易。

时区

时区在日期时间工作中至关重要。 如果忽略该问题,将应用JVM的默认时区。 更好的做法是始终指定而不是依赖于默认值。 即使您想要默认值, getDefault显式调用getDefault

当天的开头由时区定义。 巴黎的新日早些时候比蒙特利尔早。 因此,如果“昨天”表示当天的第一个时刻,则应该(a)指定时区,(b)使用withTimeAtStartOfDay调用。

乔达时间

Joda-Time 2.3中的示例代码。

 DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" ); DateTime today = DateTime.now( timeZone ); 

或者从java.util.Date对象转换。

 DateTime today = new DateTime( myJUDate, timeZone ); 

减去一天到达昨天(或前一天)。

 DateTime yesterday = today.minusDays( 1 ); DateTime yesterdayStartOfDay = today.minusDays( 1 ).withTimeAtStartOfDay(); 

默认情况下,Joda-Time和java.time以ISO 8601格式解析/生成字符串。

 String output = yesterdayStartOfDay.toString(); // Uses ISO 8601 format by default. 

使用格式化程序将完整日期作为四位数年份,一年中的两位数月份和一个月中的两位数字(yyyy-MM-dd)。 这样的格式化程序已在Joda-Time中定义。

 String outputDatePortion = ISODateFormat.date().print( yesterdayStartOfDay ); 

您可以使用Calendar类执行相同的任务:

 Calendar c = new Calendar(); //c.add(Calendar.DAY_OF_MONTH, -1); Date d = c.getTime(); 

以下为我工作

 int date = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);