1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.fourthline.cling.model.types;
17
18 import java.text.ParseException;
19 import java.text.SimpleDateFormat;
20 import java.util.Calendar;
21 import java.util.Date;
22 import java.util.TimeZone;
23
24
25
26
27 public class DateTimeDatatype extends AbstractDatatype<Calendar> {
28
29 protected String[] readFormats;
30 protected String writeFormat;
31
32 public DateTimeDatatype(String[] readFormats, String writeFormat) {
33 this.readFormats = readFormats;
34 this.writeFormat = writeFormat;
35 }
36
37 public Calendar valueOf(String s) throws InvalidValueException {
38 if (s.equals("")) return null;
39
40 Date d = getDateValue(s, readFormats);
41 if (d == null) {
42 throw new InvalidValueException("Can't parse date/time from: " + s);
43 }
44
45 Calendar c = Calendar.getInstance(getTimeZone());
46 c.setTime(d);
47
48
49
50
51
52
53
54 return c;
55 }
56
57 @Override
58 public String getString(Calendar value) throws InvalidValueException {
59 if (value == null) return "";
60 SimpleDateFormat sdt = new SimpleDateFormat(writeFormat);
61 sdt.setTimeZone(getTimeZone());
62 return sdt.format(value.getTime());
63 }
64
65 protected String normalizeTimeZone(String value) {
66 if (value.endsWith("Z")) {
67 value = value.substring(0, value.length() - 1) + "+0000";
68 } else if ((value.length() > 7)
69 && (value.charAt(value.length() - 3) == ':')
70 && ((value.charAt(value.length() - 6) == '-') || (value.charAt(value.length() - 6) == '+'))) {
71
72 value = value.substring(0, value.length() - 3) + value.substring(value.length() - 2);
73 }
74 return value;
75 }
76
77 protected Date getDateValue(String value, String[] formats) {
78
79 value = normalizeTimeZone(value);
80
81 Date d = null;
82 for (String format : formats) {
83 SimpleDateFormat sdt = new SimpleDateFormat(format);
84 sdt.setTimeZone(getTimeZone());
85 try {
86 d = sdt.parse(value);
87
88 } catch (ParseException ex) {
89
90 }
91 }
92 return d;
93 }
94
95 protected TimeZone getTimeZone() {
96 return TimeZone.getDefault();
97 }
98
99 }