package com.platform.plugs.live.utils;

import java.text.*;
import java.util.Calendar;
import java.util.Date;

/**
 * @Author TONG
 * @Date 2019/2/18 11:23
 **/
public class UTCDateFormat extends DateFormat {
    @Override
    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.HOUR_OF_DAY, -8);
        date = calendar.getTime();
        DateFormat dfD = new SimpleDateFormat("yyyy-MM-dd");
        DateFormat dfH = new SimpleDateFormat("HH:mm:ss");
        return new StringBuffer().append(dfD.format(date)).append("T").append(dfH.format(date)).append("Z");
    }

    public Date parse(String source) throws ParseException {
        source = source.replaceAll("T", " ").replaceAll("Z", "");

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(df.parse(source));
        calendar.add(Calendar.HOUR_OF_DAY, 8);
        return calendar.getTime();
    }

    @Override
    public Date parse(String source, ParsePosition pos) {
        return null;
    }

    public static void main(String[] args) throws ParseException {
        DateFormat df = new UTCDateFormat();
        Date date = df.parse("2019-03-14T14:34:55Z");
        DateFormat dfD = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(dfD.format(date));
    }
}
