JSP/Servlet | JSTL(JSP Standard Tag Library) | フォーマット fmt

fmtフォーマットは、ロケール、メッセージ形式、数値、日付形式などを表示するときに使用する。

ディレクティブ宣言

フォーマットを使用するには、JSPページの上部にJSTL format宣言が必要である。

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

formatDate

日付形式を表現するタグである。

<fmt:formatDate value="date" 
        [type="{time|date|both}"]
        [dateStyle="{default|short|medium|long|full}"] 
        [timeStyle="{default|short|medium|long|full}"]
        [pattern="customPattern"] 
        [timeZone="timeZone"] 
        [var="varName"]
        [scope="{page|request|session|application}"]/> 

属性の説明

属性 Type 説明 必須 デフォルト
value java.util.Date 表示する入力値Date 必須
type String 表示するデータが時刻、日付、または両方かを指定 date
dateStyle String 事前定義された日付形式。java.text.DateFormatクラスに定義された文法に従う。type属性が省略、date、またはbothの場合に使用
timeStyle String 事前定義された時刻形式。type属性がtimeまたはbothの場合に使用
pattern String ユーザー指定の形式スタイル
timeZone Stringまたはjava.util.TimeZone フォーマット時に表示するタイムゾーン
var String フォーマット出力結果文字列を格納するscope内の変数名
scope String varのscope

pattern属性は、より正確な日付処理を指定するために使用される。

コード 用途 表示例
G The era designator 西暦
y The year 2018
M The month 7
d The day of the month 6
h The hour (12-hour time) 12
H The hour (24-hour time) 0
m The minute 29
s The second 59
S The millisecond 494
E The day of the week
D The day of the year 187
F The day of the week in the month 1
w The week in the year 27
W The week in the month 1
a The a.m./p.m. indicator 午前
k The hour (12-hour time) 24
K The hour (24-hour time) 0
z The time zone KST
' The escape for text
'' The single quote

使用例

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html">
<html>
    <head>
        <title>JSTL fmt formatDate</title>
    </head>
    <body>
    <h1>JSTL fmt formatDate</h1>
        <c:set var="now" value="<%=new java.util.Date()%>" />

        <p><fmt:formatDate value="${now}" type="date"/></p>

        <p><fmt:formatDate value="${now}" type="time"/></p>

        <p><fmt:formatDate value="${now}" type="both"/></p>

        <p><fmt:formatDate value="${now}" type="both" dateStyle="default" timeStyle="default"/></p>

        <p><fmt:formatDate value="${now}" type="both" dateStyle="short" timeStyle="short"/></p>

        <p><fmt:formatDate value="${now}" type="both" dateStyle="medium" timeStyle="medium"/></p>

        <p><fmt:formatDate value="${now}" type="both" dateStyle="long" timeStyle="long"/></p>

        <p><fmt:formatDate value="${now}" type="both" dateStyle="full" timeStyle="full"/></p>

        <p><fmt:formatDate value="${now}" type="both" pattern="yyyy年 MM月 dd日 HH時 mm分 ss秒 E曜日"/></p>

    </body>
</html>

結果を表示すると次のようになる。

JSTL fmt formatDate

2018. 7. 6

午前 12:19:48

2018. 7. 6 午前 12:19:48

2018. 7. 6 午前 12:19:48

18. 7. 6 午前 12:19

2018. 7. 6 午前 12:19:48

2018年7月6日 (金) 午前12時19分48秒

2018年7月6日 金曜日 午前12時19分48秒 KST

2018年 07月 06日 00時 19分 48秒 金曜日