如何从日历中只获取日期而没有时间?

问题描述

我使用以下代码向日历添加一天。但是,我只想在字符串中检索没有时间的日期。这可能吗?

  Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE,1);
String dateandtime=calendar.getTime();

更新:感谢您的建议。对于像我这样的Java新手来说,类似的帖子建议太复杂了。这个问题提供的答案很简单。因此,我建议不应关闭此问题。

解决方法

这可能有帮助

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"
,

java.time

对于简单,可靠和最新的解决方案,我建议您使用java.time(现代的Java日期和时间API)进行日期工作。

    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 tutorial: Date Time解释了如何使用java.time。