李宇
2021-11-12 43ee95fbdcb6fe0a9d548d0935c23c232d5ffeaa
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
package com.nanometer.smartlab.converter;
 
import com.nanometer.smartlab.util.Utils;
import org.apache.commons.lang.StringUtils;
import org.primefaces.component.calendar.Calendar;
 
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import java.util.Date;
 
/**
 * Created by johnny on 15-5-18.
 */
@FacesConverter("timestampConvert")
public class TimestampConvert implements Converter {
 
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (component != null && component instanceof Calendar) {
            Calendar calendar = (Calendar)component;
            String pattern = calendar.getPattern();
            return Utils.formatStringToTimestamp(value, pattern);
        }
        return null;
    }
 
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        try {
            if (value instanceof String) {
                return (String) value;
            }
 
            if (value != null && value instanceof Date) {
                Date date = (Date)value;
                String pattern = null;
                if (component != null && component instanceof Calendar) {
                    Calendar calendar = (Calendar)component;
                    pattern = calendar.getPattern();
                }
                if (StringUtils.isBlank(pattern)) {
                    pattern = "yyyy-MM-dd HH:mm:ss";
                }
 
                return Utils.formatDateToString(date, pattern);
            }
 
            return null;
        } catch (Exception e) {
            return null;
        }
    }
}