4479 |
05 May 17 |
nicklas |
1 |
package net.sf.basedb.reggie.converter; |
4479 |
05 May 17 |
nicklas |
2 |
|
4479 |
05 May 17 |
nicklas |
3 |
import java.time.Instant; |
4479 |
05 May 17 |
nicklas |
4 |
import java.time.LocalDateTime; |
4479 |
05 May 17 |
nicklas |
5 |
import java.time.ZoneId; |
4479 |
05 May 17 |
nicklas |
6 |
import java.time.temporal.IsoFields; |
4479 |
05 May 17 |
nicklas |
7 |
import java.util.Date; |
4479 |
05 May 17 |
nicklas |
8 |
|
4479 |
05 May 17 |
nicklas |
9 |
/** |
4479 |
05 May 17 |
nicklas |
Value converter implementation for converting dates to a year+quarter string (eg. 2017Q1). |
4479 |
05 May 17 |
nicklas |
11 |
|
4479 |
05 May 17 |
nicklas |
@author nicklas |
4479 |
05 May 17 |
nicklas |
@since 4.10 |
4479 |
05 May 17 |
nicklas |
14 |
*/ |
4479 |
05 May 17 |
nicklas |
15 |
public class DateToQuarterConverter |
4479 |
05 May 17 |
nicklas |
16 |
implements ValueConverter<Date, String> |
4479 |
05 May 17 |
nicklas |
17 |
{ |
4479 |
05 May 17 |
nicklas |
18 |
|
4479 |
05 May 17 |
nicklas |
19 |
/** |
4479 |
05 May 17 |
nicklas |
We will never need more than this instance. |
4479 |
05 May 17 |
nicklas |
21 |
*/ |
4479 |
05 May 17 |
nicklas |
22 |
public static final DateToQuarterConverter INSTANCE = new DateToQuarterConverter(); |
4479 |
05 May 17 |
nicklas |
23 |
|
4479 |
05 May 17 |
nicklas |
24 |
/** |
4479 |
05 May 17 |
nicklas |
Use the singleton instance instead. |
4479 |
05 May 17 |
nicklas |
26 |
*/ |
4479 |
05 May 17 |
nicklas |
27 |
private DateToQuarterConverter() |
4479 |
05 May 17 |
nicklas |
28 |
{} |
4479 |
05 May 17 |
nicklas |
29 |
|
4479 |
05 May 17 |
nicklas |
30 |
/* |
4479 |
05 May 17 |
nicklas |
From the ValueConverter interface |
4479 |
05 May 17 |
nicklas |
32 |
--------------------------------- |
4479 |
05 May 17 |
nicklas |
33 |
*/ |
4479 |
05 May 17 |
nicklas |
34 |
@Override |
4479 |
05 May 17 |
nicklas |
35 |
public String convert(Date value) |
4479 |
05 May 17 |
nicklas |
36 |
{ |
4479 |
05 May 17 |
nicklas |
37 |
if (value == null) return null; |
4479 |
05 May 17 |
nicklas |
// IMPORTANT! We must use Instant.ofEpochMilli() instead of Date.toInstant() |
4479 |
05 May 17 |
nicklas |
// since java.sql.Date.toInstant() throw UnsupporterOperationException |
4479 |
05 May 17 |
nicklas |
40 |
LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(value.getTime()), ZoneId.systemDefault()); |
4479 |
05 May 17 |
nicklas |
41 |
return dateTime.getYear() + "Q" + dateTime.get(IsoFields.QUARTER_OF_YEAR); |
4479 |
05 May 17 |
nicklas |
42 |
} |
4479 |
05 May 17 |
nicklas |
43 |
// ---------------------------------- |
4479 |
05 May 17 |
nicklas |
44 |
|
4479 |
05 May 17 |
nicklas |
45 |
} |