无法更改 Java 中的日历 DAY_OF_MONTH
Can't change Calendar DAY_OF_MONTH in Java
我在 Java 日历设置中遇到了一个小问题。问题是我有这段代码 returns "1980.09.12."
.
我可以随意更改年月,但不能更改日期。
public class printableBeosztas extends HttpServlet {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.");
Calendar calHetfo;
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
setDates();
response.getWriter().append(sdf.format(calHetfo.getTime());
}
public void setDates() {
calHetfo = Calendar.getInstance();
calHetfo.set(Calendar.MONTH, 8);
calHetfo.set(Calendar.YEAR, 1980);
calHetfo.set(Calendar.DAY_OF_MONTH, 3);
}
}
有什么想法吗?
如果你使用 java.time API of Java 8+, where you can use LocalDate.of
并设置你想要的任何东西会更容易:
LocalDate ld = LocalDate.of(1980, Month.SEPTEMBER, 12);
要格式化日期,您可以使用:
String format = ld.format(DateTimeFormatter.ofPattern("yyyy.MM.dd."));
我在 Java 日历设置中遇到了一个小问题。问题是我有这段代码 returns "1980.09.12."
.
我可以随意更改年月,但不能更改日期。
public class printableBeosztas extends HttpServlet {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.");
Calendar calHetfo;
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
setDates();
response.getWriter().append(sdf.format(calHetfo.getTime());
}
public void setDates() {
calHetfo = Calendar.getInstance();
calHetfo.set(Calendar.MONTH, 8);
calHetfo.set(Calendar.YEAR, 1980);
calHetfo.set(Calendar.DAY_OF_MONTH, 3);
}
}
有什么想法吗?
如果你使用 java.time API of Java 8+, where you can use LocalDate.of
并设置你想要的任何东西会更容易:
LocalDate ld = LocalDate.of(1980, Month.SEPTEMBER, 12);
要格式化日期,您可以使用:
String format = ld.format(DateTimeFormatter.ofPattern("yyyy.MM.dd."));