トップ 履歴 一覧 カテゴリ ソース 検索 ヘルプ RSS ログイン

Source/Java/W3CDTF

INDEX

W3Cの日時の表記

W3Cのノートで示されている日時の表記法でのフォーマットと解析を行う。

日付フォーマットクラス

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
/*
 * $Id: W3cdtfDateFormat.java,v 0.0 2009/07/23 00:00:00 t-imamura Exp $
 *
 * Copyright (c) 2009 T.Imamura, All rights reserved.
 */
package w3cdtf;

import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <code>W3cdtfDateFormat</code> は、W3Cのノートで示されている日時の表記法での
 * 日付のフォーマットと解析を行うための具象クラスです。
 *
 * <h4><a name="synchronization">同期</a></h4>
 * <p>日付フォーマットは同期化されません。スレッドごとに別のフォーマットインスタンスを
 * 作成することをお勧めします。複数のスレッドがフォーマットに同時にアクセスする場合は、
 * 外部的に同期化する必要があります。</p>
 *
 * <dl>
 * <dt>W3CDTF</dt>
 * <dd>Misha Wolf and Charles Wicksteed, Date and Time Formats, 1997-12-15, W3C Note
 * <br><a href="http://www.w3.org/TR/NOTE-datetime">http://www.w3.org/TR/NOTE-datetime</a></dd>
 * </dl>
 *
 * @see DateFormat
 */
public class W3cdtfDateFormat extends DateFormat {

    /** シリアルバージョン */
    private static final long serialVersionUID = 1L;

    /** 年のみ (eg 1997) */
    public static final int YEAR = 1;

    /** 年月 (eg 1997-07) */
    public static final int YEAR_MONTH = 2;
    /** 年月 ({@link W3cdtfDateFormat#YEAR_MONTH YEAR_MONTH} の別名) */
    public static final int MONTH = YEAR_MONTH;

    /** 年月日 (eg 1997-07-16) */
    public static final int COMPLETE_DATE = 3;
    /** 年月日 ({@link W3cdtfDateFormat#COMPLETE_DATE COMPLETE_DATE} の別名) */
    public static final int DATE = COMPLETE_DATE;
    /** XML Schema date datatypes */
    public static final int XS_DATE = COMPLETE_DATE;

    /** 年月日および時分 (eg 1997-07-16T19:20+01:00) */
    public static final int COMPLETE_DATE_HOURS_MINUTE = 4;
    /** 年月日および時分 ({@link W3cdtfDateFormat#COMPLETE_DATE_HOURS_MINUTE COMPLETE_DATE_HOURS_MINUTE} の別名) */
    public static final int MINUTE = COMPLETE_DATE_HOURS_MINUTE;

    /** 年月日および時分秒 (eg 1997-07-16T19:20:30+01:00) */
    public static final int COMPLETE_DATE_SECOND = 5;
    /** 年月日および時分秒 ({@link W3cdtfDateFormat#COMPLETE_DATE_SECOND COMPLETE_DATE_SECOND} の別名) */
    public static final int SECOND = COMPLETE_DATE_SECOND;

    /** 年月日および時分秒および小数部分 (eg 1997-07-16T19:20:30.456+01:00) */
    public static final int COMPLETE_DATE_MILLISECOND = 6;
    /** 年月日および時分秒および小数部分 ({@link W3cdtfDateFormat#COMPLETE_DATE_MILLISECOND COMPLETE_DATE_MILLISECOND} の別名) */
    public static final int MILLISECOND = COMPLETE_DATE_MILLISECOND;
    /** XML Schema dateTime datatypes */
    public static final int XS_DATETIME = COMPLETE_DATE_MILLISECOND;

    /** フォーマットパターン */
    private int pattern = 0;
    /** タイムゾーンを省略する */
    private boolean omitTimeZone = false;

    /**
     * <code>W3cdtfDateFormat</code> を構築します。
     */
    public W3cdtfDateFormat() {
        this(COMPLETE_DATE_MILLISECOND, false);
    }

    /**
     * <code>W3cdtfDateFormat</code> を構築します。
     * @param pattern フォーマットパターン
     */
    public W3cdtfDateFormat(int pattern) {
        this(pattern, false);
    }

    /**
     * <code>W3cdtfDateFormat</code> を構築します。
     * @param pattern フォーマットパターン
     * @param omitTimeZone タイムゾーンを省略するか
     */
    public W3cdtfDateFormat(int pattern, boolean omitTimeZone) {
        this.pattern = pattern;
        this.omitTimeZone = omitTimeZone;
        this.calendar = Calendar.getInstance();
    }

    @Override
    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
        calendar.setTime(date);

        if (pattern >= YEAR) {
            toAppendTo.append(String.format("%04d", calendar.get(Calendar.YEAR)));
        }
        if (pattern >= YEAR_MONTH) {
            toAppendTo.append(String.format("-%02d", calendar.get(Calendar.MONTH) + 1));
        }
        if (pattern >= COMPLETE_DATE) {
            toAppendTo.append(String.format("-%02d", calendar.get(Calendar.DAY_OF_MONTH)));
        }
        if (pattern >= COMPLETE_DATE_HOURS_MINUTE) {
            toAppendTo.append(String.format("T%02d", calendar.get(Calendar.HOUR_OF_DAY)));
            toAppendTo.append(String.format(":%02d", calendar.get(Calendar.MINUTE)));
        }
        if (pattern >= COMPLETE_DATE_SECOND) {
            toAppendTo.append(String.format(":%02d", calendar.get(Calendar.SECOND)));
        }
        if (pattern >= COMPLETE_DATE_MILLISECOND) {
            toAppendTo.append(String.format(".%03d", calendar.get(Calendar.MILLISECOND)));
        }
        if (pattern >= COMPLETE_DATE_HOURS_MINUTE && !omitTimeZone) {
            int tz = (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)) / 60000;
            if (tz == 0) {
                toAppendTo.append("Z");
            } else {
                toAppendTo.append(String.format("%+03d:%02d", (tz / 60), (tz % 60)));
            }
        }

        return toAppendTo;
    }

    /** 日付文字列解析用正規表現 */
    private static final Pattern W3CDTF_PATTERN = Pattern.compile("^(\\d{4})(?:[-/.](\\d{2})(?:[-/.](\\d{2})"
            + "(?:[T ](\\d{2}):(\\d{2})(?:(?::(\\d{2})(.\\d+)?)?(?:([-+]\\d{2}):(\\d{2})|(Z))?)?)?)?)?$");

    @Override
    public Date parse(String source, ParsePosition pos) {
        if (source == null) {
            pos.setErrorIndex(pos.getIndex());
            return null;
        }
        source = source.substring(pos.getIndex());
        if (source.isEmpty()) {
            pos.setErrorIndex(pos.getIndex());
            return null;
        }
        Matcher m = W3CDTF_PATTERN.matcher(source);
        if (!m.find()) {
            pos.setErrorIndex(pos.getIndex());
            return null;
        }

        calendar.clear();
        calendar.set(Calendar.YEAR, Integer.parseInt(m.group(1)));
        calendar.set(Calendar.MONTH, (m.group(2) == null) ? 0 : Integer.parseInt(m.group(2)) - 1);
        calendar.set(Calendar.DAY_OF_MONTH, (m.group(3) == null) ? 0 : Integer.parseInt(m.group(3)));
        calendar.set(Calendar.HOUR_OF_DAY, (m.group(4) == null) ? 0 : Integer.parseInt(m.group(4)));
        calendar.set(Calendar.MINUTE, (m.group(5) == null) ? 0 : Integer.parseInt(m.group(5)));
        calendar.set(Calendar.SECOND, (m.group(6) == null) ? 0 : Integer.parseInt(m.group(6)));
        calendar.set(Calendar.MILLISECOND, (m.group(7) == null) ? 0 : (int) (Double.parseDouble(m.group(7)) * 1000.0D));
        if (m.group(8) != null) {
            int tz = ((int) (Double.parseDouble(m.group(8))) * 60 + Integer.parseInt(m.group(9))) * 60000;
            calendar.set(Calendar.ZONE_OFFSET, tz);
        } else if (m.group(10) != null) {
            calendar.set(Calendar.ZONE_OFFSET, 0);
        }
        pos.setIndex(pos.getIndex() + source.length() - 1);
        return calendar.getTime();
    }

}

テスト兼サンプル

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
package w3cdtf;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import junit.framework.TestCase;

/** <code>W3cdtfDateFormat</code> ユニットテストクラス. */
public class W3cdtfDateFormatTest extends TestCase {

    /** テスト用時刻 <code>1248320096789L = 2009-07-23T12:34:56.789+09:00 = 2009-07-23T03:34:56.789Z</code> */
    private static final long time = 1248320096789L;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
    }

    @Override
    protected void tearDown() throws Exception {
        super.tearDown();
    }

    private Date toDate(int year, int month, int date, int hour, int minute, int second, int millis, int tzh) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, date);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, second);
        calendar.set(Calendar.MILLISECOND, millis);
        calendar.set(Calendar.ZONE_OFFSET, tzh * 60 * 60000);
        return calendar.getTime();
    }

    /**
     * フォーマット.
     * <code>null</code>を指定した場合、NullPointerException となる
     * @throws Exception 例外
     */
    public void testFormat_setNull() throws Exception {
        DateFormat formater = new W3cdtfDateFormat();
        try {
            formater.format(null);
            fail("例外にならなかった");
        } catch (NullPointerException e) {
            // NullPointerException ならOK
        }
    }

    /**
     * フォーマット.
     * @throws Exception 例外
     */
    public void testFormat() throws Exception {
        DateFormat formater = new W3cdtfDateFormat();
        assertEquals("2009-07-23T12:34:56.789+09:00", formater.format(new Date(time)));
    }

    /**
     * フォーマット.
     * @throws Exception 例外
     */
    public void testFormat_UTC() throws Exception {
        DateFormat formater = new W3cdtfDateFormat();
        formater.setTimeZone(TimeZone.getTimeZone("GMT"));
        assertEquals("2009-07-23T03:34:56.789Z", formater.format(new Date(time)));
    }

    /**
     * フォーマット.
     * パターン:年月日および時分秒および小数部分
     * @throws Exception 例外
     */
    public void testFormat_MILLISECOND() throws Exception {
        DateFormat formater = new W3cdtfDateFormat(W3cdtfDateFormat.MILLISECOND);
        assertEquals("2009-07-23T12:34:56.789+09:00", formater.format(new Date(time)));
    }

    /**
     * フォーマット.
     * パターン:年月日および時分秒
     * @throws Exception 例外
     */
    public void testFormat_SECOND() throws Exception {
        DateFormat formater = new W3cdtfDateFormat(W3cdtfDateFormat.SECOND);
        assertEquals("2009-07-23T12:34:56+09:00", formater.format(new Date(time)));
    }

    /**
     * フォーマット.
     * パターン:年月日および時分
     * @throws Exception 例外
     */
    public void testFormat_MINUTE() throws Exception {
        DateFormat formater = new W3cdtfDateFormat(W3cdtfDateFormat.MINUTE);
        assertEquals("2009-07-23T12:34+09:00", formater.format(new Date(time)));
    }

    /**
     * フォーマット.
     * パターン:年月日
     * @throws Exception 例外
     */
    public void testFormat_DATE() throws Exception {
        DateFormat formater = new W3cdtfDateFormat(W3cdtfDateFormat.DATE);
        assertEquals("2009-07-23", formater.format(new Date(time)));
    }

    /**
     * フォーマット.
     * パターン:年月
     * @throws Exception 例外
     */
    public void testFormat_MONTH() throws Exception {
        DateFormat formater = new W3cdtfDateFormat(W3cdtfDateFormat.MONTH);
        assertEquals("2009-07", formater.format(new Date(time)));
    }

    /**
     * フォーマット.
     * パターン:年
     * @throws Exception 例外
     */
    public void testFormat_YEAR() throws Exception {
        DateFormat formater = new W3cdtfDateFormat(W3cdtfDateFormat.YEAR);
        assertEquals("2009", formater.format(new Date(time)));
    }

    /**
     * フォーマット.
     * パターン:年月日および時分秒および小数部分 タイムゾーン無し
     * @throws Exception 例外
     */
    public void testFormat_MILLISECOND_OmitTZ() throws Exception {
        DateFormat formater = new W3cdtfDateFormat(W3cdtfDateFormat.MILLISECOND, true);
        assertEquals("2009-07-23T12:34:56.789", formater.format(new Date(time)));
    }

    /**
     * フォーマット.
     * パターン:年月日および時分秒 タイムゾーン無し
     * @throws Exception 例外
     */
    public void testFormat_SECOND_OmitTZ() throws Exception {
        DateFormat formater = new W3cdtfDateFormat(W3cdtfDateFormat.SECOND, true);
        assertEquals("2009-07-23T12:34:56", formater.format(new Date(time)));
    }

    /**
     * フォーマット.
     * パターン:年月日および時分 タイムゾーン無し
     * @throws Exception 例外
     */
    public void testFormat_MINUTE_OmitTZ() throws Exception {
        DateFormat formater = new W3cdtfDateFormat(W3cdtfDateFormat.MINUTE, true);
        assertEquals("2009-07-23T12:34", formater.format(new Date(time)));
    }

    /**
     * パース.
     * <code>null</code>を指定した場合、ParseException となる
     * @throws Exception 例外
     */
    public void testParse_setNull() throws Exception {
        DateFormat formater = new W3cdtfDateFormat();
        try {
            formater.parse(null);
            fail("例外にならなかった");
        } catch (ParseException e) {
            // ParseException ならOK
        } catch (NullPointerException e) {
            throw e;
        }
    }

    /**
     * パース.
     * 空文字列を指定した場合、ParseException となる
     * @throws Exception 例外
     */
    public void testParse_setEmpty() throws Exception {
        DateFormat formater = new W3cdtfDateFormat();
        try {
            formater.parse("");
            fail("例外にならなかった");
        } catch (ParseException e) {
            // ParseException ならOK
        }
    }

    /**
     * パース.
     * 空文字列を指定した場合、ParseException となる
     * @throws Exception 例外
     */
    public void testParse_setErrorString() throws Exception {
        DateFormat formater = new W3cdtfDateFormat();
        try {
            formater.parse("2009/07/23 12:34:56.789+09");
            fail("例外にならなかった");
        } catch (ParseException e) {
            // ParseException ならOK
        }
    }

    /**
     * パース.
     * @throws Exception 例外
     */
    public void testParse() throws Exception {
        DateFormat formater = new W3cdtfDateFormat();
        assertEquals(new Date(time), formater.parse("2009-07-23T12:34:56.789+09:00"));
    }

    /**
     * パース.
     * @throws Exception 例外
     */
    public void testParse_UTC() throws Exception {
        DateFormat formater = new W3cdtfDateFormat();
        assertEquals(new Date(time), formater.parse("2009-07-23T03:34:56.789Z"));
    }

    /**
     * パース.
     * @throws Exception 例外
     */
    public void testParse1() throws Exception {
        DateFormat formater = new W3cdtfDateFormat();
        assertEquals(new Date(time), formater.parse("2009/07/23T12:34:56.789+09:00"));
    }

    /**
     * パース.
     * @throws Exception 例外
     */
    public void testParse2() throws Exception {
        DateFormat formater = new W3cdtfDateFormat();
        assertEquals(new Date(time), formater.parse("2009.07.23T12:34:56.789+09:00"));
    }

    /**
     * パース.
     * @throws Exception 例外
     */
    public void testParse3() throws Exception {
        DateFormat formater = new W3cdtfDateFormat();
        assertEquals(new Date(time), formater.parse("2009-07-23 12:34:56.789+09:00"));
    }

    /**
     * パース.
     * パターン:年月日および時分秒および小数部分
     * @throws Exception 例外
     */
    public void testParse_MILLISECOND() throws Exception {
        DateFormat formater = new W3cdtfDateFormat(W3cdtfDateFormat.MILLISECOND);
        assertEquals(toDate(2009, 7, 23, 12, 34, 56, 789, 8), formater.parse("2009-07-23T12:34:56.789+08:00"));
    }

    /**
     * パース.
     * パターン:年月日および時分秒
     * @throws Exception 例外
     */
    public void testParse_SECOND() throws Exception {
        DateFormat formater = new W3cdtfDateFormat(W3cdtfDateFormat.SECOND);
        assertEquals(toDate(2009, 7, 23, 12, 34, 56, 0, 8), formater.parse("2009-07-23T12:34:56+08:00"));
    }

    /**
     * パース.
     * パターン:年月日および時分
     * @throws Exception 例外
     */
    public void testParse_MINUTE() throws Exception {
        DateFormat formater = new W3cdtfDateFormat(W3cdtfDateFormat.MINUTE);
        assertEquals(toDate(2009, 7, 23, 12, 34, 0, 0, 8), formater.parse("2009-07-23T12:34+08:00"));
    }

    /**
     * パース.
     * パターン:年月日
     * @throws Exception 例外
     */
    public void testParse_DATE() throws Exception {
        DateFormat formater = new W3cdtfDateFormat(W3cdtfDateFormat.DATE);
        assertEquals(toDate(2009, 7, 23, 0, 0, 0, 0, 9), formater.parse("2009-07-23"));
    }

    /**
     * パース.
     * パターン:年月
     * @throws Exception 例外
     */
    public void testParse_MONTH() throws Exception {
        DateFormat formater = new W3cdtfDateFormat(W3cdtfDateFormat.MONTH);
        assertEquals(toDate(2009, 7, 0, 0, 0, 0, 0, 9), formater.parse("2009-07"));
    }

    /**
     * パース.
     * パターン:年
     * @throws Exception 例外
     */
    public void testParse_YEAR() throws Exception {
        DateFormat formater = new W3cdtfDateFormat(W3cdtfDateFormat.YEAR);
        assertEquals(toDate(2009, 1, 0, 0, 0, 0, 0, 9), formater.parse("2009"));
    }

    /**
     * パース.
     * パターン:年月日および時分秒および小数部分 タイムゾーン無し
     * @throws Exception 例外
     */
    public void testParse_MILLISECOND_OmitTZ() throws Exception {
        DateFormat formater = new W3cdtfDateFormat(W3cdtfDateFormat.MILLISECOND, true);
        assertEquals(toDate(2009, 7, 23, 12, 34, 56, 789, 9), formater.parse("2009-07-23T12:34:56.789"));
    }

    /**
     * パース.
     * パターン:年月日および時分秒 タイムゾーン無し
     * @throws Exception 例外
     */
    public void testParse_SECOND_OmitTZ() throws Exception {
        DateFormat formater = new W3cdtfDateFormat(W3cdtfDateFormat.SECOND, true);
        assertEquals(toDate(2009, 7, 23, 12, 34, 56, 0, 9), formater.parse("2009-07-23T12:34:56"));
    }

    /**
     * パース.
     * パターン:年月日および時分 タイムゾーン無し
     * @throws Exception 例外
     */
    public void testParse_MINUTE_OmitTZ() throws Exception {
        DateFormat formater = new W3cdtfDateFormat(W3cdtfDateFormat.MINUTE, true);
        assertEquals(toDate(2009, 7, 23, 12, 34, 0, 0, 9), formater.parse("2009-07-23T12:34"));
    }

}

最終更新時間:2009年11月29日 15時41分19秒 指摘や意見などあればSandBoxのBBSへ。

W3cdtfDateFormat.java W3cdtfDateFormatTest.java