Java将UTC格式时间转换为北京时间

UTC时间格式有很多,需要辨清自己是属于哪种格式,否则会出错

/* RFC 1123 with 2-digit Year */"EEE, dd MMM yy HH:mm:ss z",
/* RFC 1123 with 4-digit Year */"EEE, dd MMM yyyy HH:mm:ss z",   
/* RFC 1123 with no Timezone */"EEE, dd MMM yy HH:mm:ss",   
/* Variant of RFC 1123 */"EEE, MMM dd yy HH:mm:ss",   
/* RFC 1123 with no Seconds */"EEE, dd MMM yy HH:mm z",   
/* Variant of RFC 1123 */"EEE dd MMM yyyy HH:mm:ss",   
/* RFC 1123 with no Day */"dd MMM yy HH:mm:ss z",   
/* RFC 1123 with no Day or Seconds */"dd MMM yy HH:mm z",   
/* ISO 8601 slightly modified */"yyyy-MM-dd'T'HH:mm:ssZ",   
/* ISO 8601 slightly modified */"yyyy-MM-dd'T'HH:mm:ss'Z'",   
/* ISO 8601 slightly modified */"yyyy-MM-dd'T'HH:mm:sszzzz",   
/* ISO 8601 slightly modified */"yyyy-MM-dd'T'HH:mm:ss z",   
/* ISO 8601 */"yyyy-MM-dd'T'HH:mm:ssz",   
/* ISO 8601 slightly modified */"yyyy-MM-dd'T'HH:mm:ss.SSSz",   
/* ISO 8601 slightly modified */"yyyy-MM-dd'T'HHmmss.SSSz",   
/* ISO 8601 slightly modified */"yyyy-MM-dd'T'HH:mm:ss",   
/* ISO 8601 w/o seconds */"yyyy-MM-dd'T'HH:mmZ",   
/* ISO 8601 w/o seconds */"yyyy-MM-dd'T'HH:mm'Z'",   
/* RFC 1123 without Day Name */"dd MMM yyyy HH:mm:ss z",   
/* RFC 1123 without Day Name and Seconds */"dd MMM yyyy HH:mm z",   
/* Simple Date Format */"yyyy-MM-dd",   
/* Simple Date Format */"MMM dd, yyyy"};

UTC时间是世界时间,北京时间应在UTC时间+上8小时  

public static void main(String[] args) throws Exception{
        Date date = null;
        // ISO 8601 slightly modified */"yyyy-MM-dd'T'HH:mm:ss'Z'",
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        // 2019-05-21T08:44:00Z 对应的时间格式 yyyy-MM-dd'T'HH:mm:ss'Z'
        date = sdf.parse("2019-05-21T08:44:00Z");
        System.out.println("UTC时间:"+date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR)+8);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = calendar.getTime();
        String date2 = simpleDateFormat.format(calendar.getTime());
        System.out.println("北京时间:"+date2);

    }

 

你可能感兴趣的:(Java)