DateConverter.java
2.53 KB
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
/**
* Copyright © 2015-2018 ODM All rights reserved.
*/
package com.thinkgem.jeesite.modules.act.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 日期转换类
* @author ThinkGem
* @version 2013-11-03
*/
public class DateConverter implements Converter {
private static final Logger logger = LoggerFactory.getLogger(DateConverter.class);
private static final String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
private static final String DATETIME_PATTERN_NO_SECOND = "yyyy-MM-dd HH:mm";
private static final String DATE_PATTERN = "yyyy-MM-dd";
private static final String MONTH_PATTERN = "yyyy-MM";
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object convert(Class type, Object value) {
Object result = null;
if (type == Date.class) {
try {
result = doConvertToDate(value);
} catch (ParseException e) {
e.printStackTrace();
}
} else if (type == String.class) {
result = doConvertToString(value);
}
return result;
}
/**
* Convert String to Date
*
* @param value
* @return
* @throws ParseException
*/
private Date doConvertToDate(Object value) throws ParseException {
Date result = null;
if (value instanceof String) {
result = DateUtils.parseDate((String) value, new String[] { DATE_PATTERN, DATETIME_PATTERN,
DATETIME_PATTERN_NO_SECOND, MONTH_PATTERN });
// all patterns failed, try a milliseconds constructor
if (result == null && StringUtils.isNotEmpty((String) value)) {
try {
result = new Date(new Long((String) value).longValue());
} catch (Exception e) {
logger.error("Converting from milliseconds to Date fails!");
e.printStackTrace();
}
}
} else if (value instanceof Object[]) {
// let's try to convert the first element only
Object[] array = (Object[]) value;
if (array.length >= 1) {
value = array[0];
result = doConvertToDate(value);
}
} else if (Date.class.isAssignableFrom(value.getClass())) {
result = (Date) value;
}
return result;
}
/**
* Convert Date to String
*
* @param value
* @return
*/
private String doConvertToString(Object value) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATETIME_PATTERN);
String result = null;
if (value instanceof Date) {
result = simpleDateFormat.format(value);
}
return result;
}
}