解析GMT+N时区,返回日期类型

涉及到正则表达式,时区转换。

/**

    * 

    * 按格式 yyyy-MM-dd HH:mm:ss 以指定GMT时区进行解析,返回对应的当前系统时区当地时间。

    * @param dateString  格式 yyyy-MM-dd HH:mm:ss

    * @param timeZoneGMT  格式GMT+8,GMT-7,GMT+09:00,GMT-06:00

    * @return

    * @throws ParseException

    */

  public static Date parseGMTDate(String dateString, String timeZoneGMT) throws ParseException {

      String timeZoneGMTRegex = "^GMT[-+](\\d{1,2})(:?(\\d\\d))?$";

      if (timeZoneGMT.matches(timeZoneGMTRegex)) {

      TimeZone timeZone = TimeZone.getTimeZone(timeZoneGMT);

      return parseDate(dateString, "yyyy-MM-dd HH:mm:ss", timeZone,null);

      }

 

      throw new ParseException(String.format("input GMT time zone format ['%s'] error ",timeZoneGMT),0);

  }

 

 

/**

    * 按指定格式 <code>pattern</code> 和指定时区进行解析,返回对应的当前系统时区当地时间。

    *

    * @param date

    * @param pattern  格式参考 {@link SimpleDateFormat}

    * @param timeZone

    * @return

    * @throws ParseException

    */

    public static Date parseDate(String date, String pattern, TimeZone timeZone,Locale locale) throws ParseException {

        Objects.requireNonNull(date, "date");

        Objects.requireNonNull(pattern, "pattern");

        SimpleDateFormat format = getSimpleDateFormat(pattern, timeZone, locale);

        return format.parse(date);

    }

 

 

private static SimpleDateFormat getSimpleDateFormat(String pattern, TimeZone timeZone, Locale locale) {

        if (timeZone == null) {

            timeZone = TimeZone.getDefault();

        }

        // 每次实例化 SimpleDateFormat 需要解析 pattern,非常耗时,但其本身又是线程不安全的,因此借用 ThreadLocal

        LRU<String, SimpleDateFormat> formatMap = formats.get();

        if (formatMap == null) {

            formatMap = new LRU<String, SimpleDateFormat>(128);

            formats.set(formatMap);

        }

        String formatId = pattern + timeZone.getID();

        SimpleDateFormat format = formatMap.get(formatId);

        if (format == null) {

            if(locale != null){

                format = new SimpleDateFormat(pattern,locale);

            }else{

                format = new SimpleDateFormat(pattern);

            }

            if (!format.getTimeZone().equals(timeZone)) {

                format.setTimeZone(timeZone);

            }

            formatMap.put(formatId, format);

        }

        return format;

    }

posted @ 2019-05-22 21:31  windpoplar  阅读(1695)  评论(0编辑  收藏  举报