java UTC時間和local時間相互轉換
1、local時間轉UTC時間
/**
* local時間轉換成UTC時間
* @param localTime
* @return
*/
public static Date localToUTC(String localTime) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date localDate= null;
try {
localDate = sdf.parse(localTime);
} catch (ParseException e) {
e.printStackTrace();
}
long localTimeInMillis=localDate.getTime();
/** long時間轉換成Calendar */
Calendar calendar= Calendar.getInstance();
calendar.setTimeInMillis(localTimeInMillis);
/** 取得時間偏移量 */
int zoneOffset = calendar.get(java.util.Calendar.ZONE_OFFSET);
/** 取得夏令時差 */
int dstOffset = calendar.get(java.util.Calendar.DST_OFFSET);
/** 從本地時間里扣除這些差量,即可以取得UTC時間*/
calendar.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset));
/** 取得的時間就是UTC標准時間 */
Date utcDate=new Date(calendar.getTimeInMillis());
return utcDate;
}
2、UTC時間轉local時間
/**
* utc時間轉成local時間
* @param utcTime
* @return
*/
public static Date utcToLocal(String utcTime){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date utcDate = null;
try {
utcDate = sdf.parse(utcTime);
} catch (ParseException e) {
e.printStackTrace();
}
sdf.setTimeZone(TimeZone.getDefault());
Date locatlDate = null;
String localTime = sdf.format(utcDate.getTime());
try {
locatlDate = sdf.parse(localTime);
} catch (ParseException e) {
e.printStackTrace();
}
return locatlDate;
}

