使用date获取昨天的date

以下函数产生今天的date; 我怎样才能使它只产生昨天的date?

private String toDate() { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); return dateFormat.format(date).toString(); } 

这是输出:

 2012-07-10 

我只需要像下面这样的昨天的date。 有没有可能在我的function呢?

 2012-07-09 

你正在减去错误的数字:

改用Calendar

 private Date yesterday() { final Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); return cal.getTime(); } 

然后,将您的方法修改为以下内容:

 private String getYesterdayDateString() { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); return dateFormat.format(yesterday()); } 

看到

  • IDEOne演示

你可以做以下事情:

 private Date getMeYesterday(){ return new Date(System.currentTimeMillis()-24*60*60*1000); } 

注意:如果您想要更进一步的落后date乘以24 * 60 * 60 * 1000的天数,例如:

 private Date getPreviousWeekDate(){ return new Date(System.currentTimeMillis()-7*24*60*60*1000); } 

同样,您可以通过将值添加到System.currentTimeMillis()来获得将来的date,例如:

 private Date getMeTomorrow(){ return new Date(System.currentTimeMillis()+24*60*60*1000); } 
  Calendar cal = Calendar.getInstance(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); System.out.println("Today's date is "+dateFormat.format(cal.getTime())); cal.add(Calendar.DATE, -1); System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime())); 

使用日历Api

试试这个:

 private String toDate() { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); // Create a calendar object with today date. Calendar is in java.util pakage. Calendar calendar = Calendar.getInstance(); // Move calendar to yesterday calendar.add(Calendar.DATE, -1); // Get current date of calendar which point to the yesterday now Date yesterday = calendar.getTime(); return dateFormat.format(yesterday).toString(); } 

尝试这个;

  public String toDate() { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); return dateFormat.format(cal.getTime()); } 
 Calendar cal = Calendar.getInstance(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); System.out.println("Today's date is "+dateFormat.format(cal.getTime())); cal.add(Calendar.DATE, -1); System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime())); 

从您的代码更改:

 private String toDate(long timestamp) { Date date = new Date (timestamp * 1000 - 24 * 60 * 60 * 1000); return new SimpleDateFormat("yyyy-MM-dd").format(date).toString(); 

}

但是你用日历做得更好。

没有直接的function来获取昨天的date。

要获取昨天的date,您需要使用Calendar减去-1