1
|
package eu.dnetlib.openaire.common;
|
2
|
|
3
|
import java.text.FieldPosition;
|
4
|
import java.util.*;
|
5
|
|
6
|
import com.fasterxml.jackson.databind.util.StdDateFormat;
|
7
|
|
8
|
public class RFC3339DateFormat extends StdDateFormat {
|
9
|
|
10
|
private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC");
|
11
|
|
12
|
// Same as ISO8601DateFormat but serializing milliseconds.
|
13
|
@Override
|
14
|
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
|
15
|
String value = format(date, true, TIMEZONE_Z, Locale.US);
|
16
|
toAppendTo.append(value);
|
17
|
return toAppendTo;
|
18
|
}
|
19
|
|
20
|
/**
|
21
|
* Format date into yyyy-MM-ddThh:mm:ss[.sss][Z|[+-]hh:mm]
|
22
|
*
|
23
|
* @param date the date to format
|
24
|
* @param millis true to include millis precision otherwise false
|
25
|
* @param tz timezone to use for the formatting (UTC will produce 'Z')
|
26
|
* @return the date formatted as yyyy-MM-ddThh:mm:ss[.sss][Z|[+-]hh:mm]
|
27
|
*/
|
28
|
private static String format(Date date, boolean millis, TimeZone tz, Locale loc) {
|
29
|
Calendar calendar = new GregorianCalendar(tz, loc);
|
30
|
calendar.setTime(date);
|
31
|
|
32
|
// estimate capacity of buffer as close as we can (yeah, that's pedantic ;)
|
33
|
StringBuilder sb = new StringBuilder(30);
|
34
|
sb.append(String.format(
|
35
|
"%04d-%02d-%02dT%02d:%02d:%02d",
|
36
|
calendar.get(Calendar.YEAR),
|
37
|
calendar.get(Calendar.MONTH) + 1,
|
38
|
calendar.get(Calendar.DAY_OF_MONTH),
|
39
|
calendar.get(Calendar.HOUR_OF_DAY),
|
40
|
calendar.get(Calendar.MINUTE),
|
41
|
calendar.get(Calendar.SECOND)
|
42
|
));
|
43
|
if (millis) {
|
44
|
sb.append(String.format(".%03d", calendar.get(Calendar.MILLISECOND)));
|
45
|
}
|
46
|
|
47
|
int offset = tz.getOffset(calendar.getTimeInMillis());
|
48
|
if (offset != 0) {
|
49
|
int hours = Math.abs((offset / (60 * 1000)) / 60);
|
50
|
int minutes = Math.abs((offset / (60 * 1000)) % 60);
|
51
|
sb.append(String.format("%c%02d:%02d",
|
52
|
(offset < 0 ? '-' : '+'),
|
53
|
hours, minutes));
|
54
|
} else {
|
55
|
sb.append('Z');
|
56
|
}
|
57
|
return sb.toString();
|
58
|
}
|
59
|
|
60
|
}
|