重新格式化主页里的日期

现在,我们知道了这些工具类,可以使用它们改变日期在我们的主页里的呈现方式。为了不在HomeController里写如下代码:

  1. SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy");
  2. Calendar cal = Calendar.getInstance();
  3. WebContext ctx = new WebContext(request, servletContext, request.getLocale());
  4. ctx.setVariable("today", dateFormat.format(cal.getTime()));
  5. templateEngine.process("home", ctx, response.getWriter());

我们可以这样做:

  1. WebContext ctx =
  2. new WebContext(request, response, servletContext, request.getLocale());
  3. ctx.setVariable("today", Calendar.getInstance());
  4. templateEngine.process("home", ctx, response.getWriter());

然后在视图层格式化日期:

  1. <p>
  2. Today is: <span th:text="${#calendars.format(today,'dd MMMM yyyy')}">13 May 2011</span>
  3. </p>