如何从日历中仅获取日期而不包含时间?

huangapple go评论90阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年10月19日 21:17:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/64428154.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定