1
2
3
4
5
6
7
8
9 package jp.sourceforge.jindolf.corelib;
10
11 import java.util.Calendar;
12 import java.util.GregorianCalendar;
13 import java.util.TimeZone;
14 import java.util.regex.Matcher;
15 import java.util.regex.Pattern;
16
17
18
19
20 final class DateUtils{
21
22 private static final Pattern ISO8601_PATTERN;
23 private static final String REG_PLUS = "\\+";
24 private static final String REG_HYPHEN = "\\-";
25
26 static{
27 StringBuilder txt = new StringBuilder();
28
29 String gYear = "([0-9][0-9][0-9][0-9])";
30 String gMonth = "([0-1][0-9])";
31 String gDay = "([0-3][0-9])";
32
33 txt.append(gYear).append(REG_HYPHEN);
34 txt.append(gMonth).append(REG_HYPHEN);
35 txt.append(gDay);
36
37 txt.append('T');
38
39 String gHour = "([0-2][0-9])";
40 String gMinute = "([0-5][0-9])";
41 String gSecond = "([0-6][0-9])";
42
43 txt.append(gHour).append(':');
44 txt.append(gMinute).append(':');
45 txt.append(gSecond);
46
47 String diffHour = "[" + REG_PLUS + REG_HYPHEN + "][0-2][0-9]";
48 String diffMin = "(?:" + ":?[0-5][0-9]" + ")?";
49 String gTimezone = "(" + diffHour + diffMin + "|Z)";
50
51 txt.append(gTimezone);
52
53 String iso8601Regex = txt.toString();
54
55 ISO8601_PATTERN = Pattern.compile(iso8601Regex);
56 }
57
58
59
60
61
62 private DateUtils(){
63 assert false;
64 return;
65 }
66
67
68
69
70
71
72
73
74
75 public static long parseISO8601(CharSequence date)
76 throws IllegalArgumentException {
77 Matcher matcher = ISO8601_PATTERN.matcher(date);
78 if( ! matcher.matches() ){
79 throw new IllegalArgumentException(date.toString());
80 }
81
82 int gid = 1;
83 String yearStr = matcher.group(gid++);
84 String monthStr = matcher.group(gid++);
85 String dayStr = matcher.group(gid++);
86 String hourStr = matcher.group(gid++);
87 String minuteStr = matcher.group(gid++);
88 String secondStr = matcher.group(gid++);
89 String tzString = matcher.group(gid++);
90
91 int year = Integer.parseInt(yearStr);
92 int month = Integer.parseInt(monthStr);
93 int day = Integer.parseInt(dayStr);
94 int hour = Integer.parseInt(hourStr);
95 int minute = Integer.parseInt(minuteStr);
96 int second = Integer.parseInt(secondStr);
97
98 String tzID;
99 if( tzString.compareToIgnoreCase("Z") == 0 ) tzID = "GMT+00:00";
100 else tzID = "GMT" + tzString;
101 TimeZone timezone = TimeZone.getTimeZone(tzID);
102
103 Calendar calendar = new GregorianCalendar();
104 calendar.clear();
105 calendar.setTimeZone(timezone);
106 calendar.set(year, month - 1, day, hour, minute, second);
107
108 long result = calendar.getTimeInMillis();
109
110 return result;
111 }
112
113 }