如何在 JSP 中格式化日期?


<fmt:formatDate> 标签用于以多种方式格式化日期。

属性

<fmt:formatDate> 标签具有以下属性:

属性描述必需默认值
要显示的日期值
typeDATE、TIME 或 BOTHdate
dateStyleFULL、LONG、MEDIUM、SHORT 或 DEFAULTdefault
timeStyleFULL、LONG、MEDIUM、SHORT 或 DEFAULTdefault
pattern自定义格式模式
timeZone显示日期的时间区域默认时区
var存储格式化日期的变量的名称打印到页面
scope存储格式化日期的变量的作用域page

pattern 属性用于指定更精确的日期处理:

代码用途示例
G纪元指示符AD
y年份2002
M月份四月 & 04
d月份中的日期20
h小时(12 小时制)12
H小时(24 小时制)0
m分钟45
s52
S毫秒970
E星期几星期二
D一年中的日期180
F一个月中的星期几2(一个月中的第二个星期三)
w一年中的星期27
W一个月中的星期2
a上午/下午指示符PM
k小时(12 小时制)24
K小时(24 小时制)0
z时区中央标准时间
'
文本的转义
''
单引号

示例

<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
<html>
   <head>
      <title>JSTL fmt:dateNumber Tag</title>
   </head>
   <body>
      <h3>Number Format:</h3>
      <c:set var = "now" value = "<% = new java.util.Date()%>" />
      <p>Formatted Date (1): <fmt:formatDate type = "time" value = "${now}" /></p>
      <p>Formatted Date (2): <fmt:formatDate type = "date" value = "${now}" /></p>
      <p>Formatted Date (3): <fmt:formatDate type = "both" value = "${now}" /></p>
      <p>Formatted Date (4): <fmt:formatDate type = "both" dateStyle = "short" timeStyle = "short" value = "${now}" /></p>
      <p>Formatted Date (5): <fmt:formatDate type = "both" dateStyle = "medium" timeStyle = "medium" value = "${now}" /></p>
      <p>Formatted Date (6): <fmt:formatDate type = "both" dateStyle = "long" timeStyle = "long" value = "${now}" /></p>
      <p>Formatted Date (7): <fmt:formatDate pattern = "yyyy-MM-dd" value = "${now}" /></p>
   </body>
</html>

以上代码将生成以下结果:

Date Format:
Formatted Date (1): 14:27:18
Formatted Date (2): 23-Sep-2010
Formatted Date (3): 23-Sep-2010 14:27:18
Formatted Date (4): 23/09/10 14:27
Formatted Date (5): 23-Sep-2010 14:27:18
Formatted Date (6): 23 September 2010 14:27:18 GST
Formatted Date (7): 2010-09-23

更新于: 30-Jul-2019

5K+ 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.