在有些软件中,可能须要展现一些时间信息,而这些信息多是Server以UTC格式或Unix timestamp 格式推送过来的,终端可能须要将这些转换为本地时间展现。服务器
终端的制式多是12小时制、也多是24小时制的spa
今天就遇到将utc时间格式转换为GMTorm
HH:返回的是24小时制的时间字符串
hh:返回的是12小时制的时间get
下面就是转换的类型代码,固然服务器的格式 2013-06-13T14:15:44.000io
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
form
根据服务器格式修改为对应的就好。软件
/* 将Server传送的UTC时间转换为指定时区的时间 */
@SuppressLint("SimpleDateFormat")
public String converTime(String srcTime, TimeZone timezone) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
SimpleDateFormat dspFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String convertTime;
Date result_date;
long result_time = 0;
// 若是传入参数异常,使用本地时间
if (null == srcTime)
result_time = System.currentTimeMillis();
else {
try { // 将输入时间字串转换为UTC时间
sdf.setTimeZone(TimeZone.getTimeZone("GMT00:00"));
result_date = sdf.parse(srcTime);
result_time = result_date.getTime();
} catch (Exception e) { // 出现异常时,使用本地时间
result_time = System.currentTimeMillis();
dspFmt.setTimeZone(TimeZone.getDefault());
convertTime = dspFmt.format(result_time);
return convertTime;
}
}
// 设定时区
dspFmt.setTimeZone(timezone);
convertTime = dspFmt.format(result_time);
return convertTime;
}
srcTime就是上面传的2013-06-13T14:15:44.000字符串,timezone 就是你本身想转换的时区,好比我转换北京东八区,TimeZone.getTimeZone("GMT+8")这样就转换成功了很是方便。date