使用日期[duplicate]获取昨天的日期(Get yesterday's date using Date [duplicate])

编程入门 行业动态 更新时间:2024-10-26 12:22:56
使用日期[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-09

This question already has an answer here:

How to check if a date Object equals yesterday? 8 answers

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(); }

This is the output:

2012-07-10

I 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

更多推荐

本文发布于:2023-08-03 18:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1396241.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期   昨天   duplicate   Date   yesterday

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!