![](/img/trans.png)
[英]Java Calendar instance increments DAY_OF_MONTH as a side effect of decrementing (only) HOUR or MINUTE
[英]Can't change Calendar DAY_OF_MONTH in Java
我在Java日歷設置中有一個小問題。 問題是我有此代碼,它返回"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 8+的java.time API,則可以更輕松,在Java 8+中可以使用LocalDate.of
並設置所需的內容:
LocalDate ld = LocalDate.of(1980, Month.SEPTEMBER, 12);
要格式化日期,您可以使用:
String format = ld.format(DateTimeFormatter.ofPattern("yyyy.MM.dd."));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.