【发布时间】:2020-06-13 21:39:59
【问题描述】:
我想在 Java 中使用 Calender 获得前一天的信息。我正在使用下面的代码。
Calendar now = Calendar.getInstance();
now.add(Calendar.DATE, -1);
now.add(Calendar.MONTH, -2);
myDate = now.get(Calendar.MONTH) + "/" + now.get(Calendar.DATE) + "/" + now.get(Calendar.YEAR);
System.out.println(myDate);
输出:2/31/2020
上述问题并非一直有效。如上所述,如果当前日期为03/01/2020,您将获得上述结果。但是二月不能有31。 Calendar lib 中是否有一个选项来处理这个问题?
如果我使用下面的格式,它会给出完全不同的值。
Calendar now = Calendar.getInstance();
now.add(Calendar.DATE, -1);
now.add(Calendar.MONTH, -2);
SimpleDateFormat df = new SimpleDateFormat("MM/DD/YYYY");
String myDate= df.format(now.getTime());
System.out.println(myDate);
输出:03/91/2020
【问题讨论】:
-
我建议你不要使用
Calendar和SimpleDateFormat。这些类设计不佳且早已过时,后者尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time API 的LocalDate和DateTimeFormatter。 -
您在哪一天运行了 sn-ps?问是因为我找不到重现您的结果的方法。当我今天(2020 年 3 月 2 日)跑步时,我从第一个 sn-p 得到
0/1/2020,从第二个 sn-p 得到01/01/2020。假设你在 3 月 1 日跑步,我会得到11/29/2019和12/363/2019。