Java中不同时区时间的转换
2017-11-01 11:30
946 查看
/** * 时区 时间转换方法:将传入的时间(可能为其他时区)转化成目标时区对应的时间 * @param sourceTime 时间格式必须为:yyyy-MM-dd HH:mm:ss * @param sourceId 入参的时间的时区id 比如:+08:00 * @param targetId 要转换成目标时区id 比如:+09:00 * @param reFormat 返回格式 默认:yyyy-MM-dd HH:mm:ss * @return string 转化时区后的时间 */ public static String timeConvert(String sourceTime, String sourceId, String targetId,String reFormat){ //校验入参是否合法 if (null == sourceId || "".equals(sourceId) || null == targetId || "".equals(targetId) || null == sourceTime || "".equals(sourceTime)){ return null; } if(StringUtil.isEmptyString(reFormat)){ reFormat = "yyyy-MM-dd HH:mm:ss"; } //校验 时间格式必须为:yyyy-MM-dd HH:mm:ss String reg = "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$"; if (!sourceTime.matches(reg)){ return null; } try{ //时间格式 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //根据入参原时区id,获取对应的timezone对象 TimeZone sourceTimeZone = TimeZone.getTimeZone("GMT"+sourceId); //设置SimpleDateFormat时区为原时区(否则是本地默认时区),目的:用来将字符串sourceTime转化成原时区对应的date对象 df.setTimeZone(sourceTimeZone); //将字符串sourceTime转化成原时区对应的date对象 java.util.Date sourceDate = df.parse(sourceTime); //开始转化时区:根据目标时区id设置目标TimeZone TimeZone targetTimeZone = TimeZone.getTimeZone("GMT"+targetId); //设置SimpleDateFormat时区为目标时区(否则是本地默认时区),目的:用来将字符串sourceTime转化成目标时区对应的date对象 df.setTimeZone(targetTimeZone); //得到目标时间字符串 String targetTime = df.format(sourceDate); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); java.util.Date date = sdf.parse(targetTime); sdf = new SimpleDateFormat(reFormat); return sdf.format(date); } catch (ParseException e){ e.printStackTrace(); } return null; }
相关文章推荐
- utc时间和不同时区之间的转换程序
- JAVA学习17_Java时区转换及时间格式
- java获取不同时区的时间字符串
- 关于时间不同时区的转换问题
- Java时区转换及时间格式
- 日期时间不同时区转换
- java导入excel表格时间类型转换格林时间制时区问题
- iOS---开发时间戳与时间,时区的转换,汉字与UTF8,16进制的转换
- Java转换Json日期/Date(1487053489965+0800)/格式以及js时间格式 Tue Feb 14 2017 14:06:32 GMT+0800
- java 时间与字符串之间的转换
- Java实现时间和时间戳相互转换
- java 时间纪元与时区介绍
- java 对带T的美国时间转换方法
- Python 调用datetime或者time获取时间的时候以及时间转换,最好设置一下时区 否则会出现相差8个小时的情况
- java对世界各个时区(TimeZone)的通用转换处理方法
- java 毫秒转换成时,分,秒,毫秒 && 根据开始时间和天数,计算出几天后的时间
- java时间与日期转换
- Java24小时制和12小时制的相互转换,时间自定义
- Json时间转换中时间自动加时区的解决办法
- Java字节序(不同语言中的网络数据传输时字节序列转换)