英文:
How to get only date without time from calendar?
问题
我使用以下代码向日历添加一天。然而,我希望仅以字符串形式检索日期,而不包括时间。这是否有可能?
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DATE, 1);
String date = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
更新:感谢您的建议。类似的帖子建议对于像我这样的Java新手来说过于复杂。本问题提供的答案很简单。这就是为什么我建议不要关闭这个问题。
英文:
I use the following code to add one day to the calendar. However, I want to retrieve in a string only the date without the time. Is this somehow possible?
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DATE,1);
String dateandtime=calendar.getTime();
Update: Thanks for your suggestions. The similar posts suggested is too complex for a newbie like me in java. The answer provided in this question is simple. That is why I suggest this question should not be closed.
答案1
得分: 3
这可能会有所帮助
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
// 输出 "2020-10-19"
英文:
This might help
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
// Output "2020-10-19"
答案2
得分: 0
## java.time
对于一个简单、可靠且最新的解决方案,我建议您在处理日期时使用现代的 Java 日期和时间 API - java.time。
LocalDate today = LocalDate.now(ZoneId.of("Europe/Athens"));
LocalDate tomorrow = today.plusDays(1);
System.out.println(tomorrow);
当我刚刚运行这个片段(10月19日),输出是:
> 2020-10-20
`LocalDate` 表示不带时间和时区的日期,因此在我看来,这正是您所需的,既没有多余的部分,也没有少了的部分。
如果要转换为字符串,您可以使用 `tomorrow.toString()` 或者使用 `DateTimeFormatter`。如何使用后者,请搜索一下,有很多地方有描述。
**链接:** [Oracle 教程:日期时间](https://docs.oracle.com/javase/tutorial/datetime/) 解释了如何使用 java.time。
英文:
java.time
For a simple, reliable and up-to-date solution I recommend that you use java.time, the modern Java date and time API, for your date work.
LocalDate today = LocalDate.now(ZoneId.of("Europe/Athens"));
LocalDate tomorrow = today.plusDays(1);
System.out.println(tomorrow);
When I ran this snippet just now (19 October), the output was:
> 2020-10-20
A LocalDate
is a date without time of day (and without time zone), so it seems to me that this gives you exactly what you need, no more, no less.
For a string you may use tomorrow.toString()
or use a DateTimeFormatter
. Search for how to do the latter, it’s described in many places.
Link: Oracle tutorial: Date Time explaining how to use java.time.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论