package com.huatek.busi.ws.util;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;

/**
 * XStream日志转换converter
 * 
 * @author anker_cheng
 * @date 2019/08/23
 */
public class XStreamYMDDateConverter extends AbstractSingleValueConverter {
    private static String PATTERN = "yyyy-MM-dd HH:mm:ss";
    private final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(PATTERN);

    @Override
    public boolean canConvert(@SuppressWarnings("rawtypes") Class type) {
        return type.equals(LocalDateTime.class);
    }

    @Override
    public Object fromString(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        if (str.length() > PATTERN.length()) {
            return LocalDateTime.parse(str.subSequence(0, PATTERN.length()), FORMATTER);
        }
        return LocalDateTime.parse(str, FORMATTER);
    }

    @Override
    public String toString(Object obj) {
        if (obj == null) {
            return null;
        }
        return FORMATTER.format((LocalDateTime)obj);
    }
}
