您的位置:首页 > 移动开发 > Android开发

Android 转换UTC时间:2013-06-13T14:15:44.000的时间格式 为GMT时间

2015-07-06 10:36 716 查看
在有些软件中,可能需要展示一些时间信息,而这些信息可能是Server以UTC格式或Unix timestamp 格式推送过来的,终端可能需要将这些转换为本地时间展示。

终端的制式可能是12小时制、也可能是24小时制的

今天就遇到将utc时间格式转换为GMT

 HH:返回的是24小时制的时间

    hh:返回的是12小时制的时间

下面就是转换的类型代码,当然服务器的格式 2013-06-13T14:15:44.000

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");

根据服务器格式修改成对应的就好。

/* 将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")这样就转换成功了非常方便。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: