使用Date获取昨天的日期 [英] Get yesterday's date using Date
本文介绍了使用Date获取昨天的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下函数生成今天的日期;如何才能让它只在昨天的日期生效?
The following function produces today's date; how can I make it produce only yesterday's 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
我只需要昨天的日期如下。是否可以在我的功能中执行此操作?
I only need yesterday's date like below. Is it possible to do this in my function?
2012-07-09
推荐答案
您正在减去错误的数字:
You are subtracting the wrong number:
使用日历
代替:
private Date yesterday() {
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return cal.getTime();
}
然后,将您的方法修改为以下内容:
Then, modify your method to the following:
private String getYesterdayDateString() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return dateFormat.format(yesterday());
}
/ strong>
See
- IDEOne Demo
这篇关于使用Date获取昨天的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文