Java:格林威治时间(GMT)字符串转Date

版权声明:https://blog.csdn.net/xianzhuo_sky https://blog.csdn.net/xianzhuo_sky/article/details/82803945

今天要处理从前端传来的日期参数,穿来的是一个GMT格式的字符串,类似于这种

Thu May 18 2018 00:00:00 GMT+0800 (中国标准时间)

将字符串转成java.util.Date类型的做法是使用SimpleDateFormat,SimpleDateFormat有一个pattern参数用于匹配字符串里的时间数据。
我按照网上方法将pattern设置为"EEE MMM dd yyyy hh:mm:ss z",进行转换时报错Unparseable date。
经过反复试验,我发现我所使用的SimpleDateFormat无法识别pattern中的EEE、MMM等标记,只能识别dd、MM、yyyy、hh、mm、ss等常用标记。
如果将GMT字符串中的星期和月份的英文简写替换成阿拉伯数字,再设置相应的pattern就可以转换了。

以下是我写的一个通用的格林威治时间(GMT)字符串转Date方法

    /**
     * 格林威治时间(GMT) 字符串转Date
     * 目前只有这种方法可行
     * @param strDate Thu May 18 2017 00:00:00 GMT+0800 (中国标准时间)
     */
    public static Date parseGMT(String strDate) throws ParseException {
        if (strDate != null && strDate.trim().length() > 0) {
            strDate = strDate.substring(4,24).replace(" ","/");
            strDate = strDate.replace("Jan","01");
            strDate = strDate.replace("Feb","02");
            strDate = strDate.replace("Mar","03");
            strDate = strDate.replace("Apr","04");
            strDate = strDate.replace("May","05");
            strDate = strDate.replace("Jun","06");
            strDate = strDate.replace("Jul","07");
            strDate = strDate.replace("Aug","08");
            strDate = strDate.replace("Sep","09");
            strDate = strDate.replace("Oct","10");
            strDate = strDate.replace("Nov","11");
            strDate = strDate.replace("Dec","12");
            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy/HH:mm:ss");
            Date date = sdf.parse(strDate);
            return date;
        }
        return null;
    }

猜你喜欢

转载自blog.csdn.net/xianzhuo_sky/article/details/82803945