使用日期[duplicate]获取昨天的日期(Get yesterday's date using Date [duplicate])
这个问题已经在这里有一个答案:
如何检查日期对象是否等于昨天? 8答案以下功能生成今天的日期; 如何才能让它只在昨天的日期生产?
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我只需要昨天的日期如下。 有可能在我的功能吗?
2012-07-09This question already has an answer here:
How to check if a date Object equals yesterday? 8 answersThe 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(); }This is the output:
2012-07-10I only need yesterday's date like below. Is it possible to do this in my 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演示You are subtracting the wrong number:
Use Calendar instead:
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()); }See
IDEOne Demo更多推荐
发布评论