孤灯野火
畅想的天空
posts - 2,comments - 4,trackbacks - 0

Java时区的转换
逻辑如下:
    
1.明确你要转的当前时间所在的时区

2.明确你要转向时间所在的时区

3.获取当前时间所在时区相对GMT的偏移量

4.当前时间-相对GMT的偏移量来获得当前时间的GMT的值

5.GMT的值+转向时区相对GMT的偏移量获取转向时区的时间值

例如:你要从GMT+8时间转向GMT+7时间
sourceTimeZone 为GMT+8

targetTimeZone为GMT+7

/**
 *
 */
package test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;


public class DateTimeUtil {
 
 static String DEFAULT_TIMEZONE = "GMT+8";
 static String DEFAULT_FORMAT = "d-MMM-yyyy HH:mm (z)";

 /**
  * 转换时间时区
  * @param convertString  需要转的时间字符串
  * @param format  格式话字符串 例如d-MMM-yyyy HH:mm (z)
  * @param sourceTimeZone 源时间时区
  * @param targetTimeZone 目标时间时区
  * @return
  * @throws ParseException
  */
 public static Date ConverDateGMT(String convertString,String format,String sourceTimeZone,String targetTimeZone) throws ParseException
 {
  
  Date date=null;
  

  if(isEmpty(sourceTimeZone)){
   sourceTimeZone = DEFAULT_TIMEZONE;
  }
  
  if(isEmpty(targetTimeZone)){
   targetTimeZone = DEFAULT_TIMEZONE;
  }
  
  if(isEmpty(format)){
   format = DEFAULT_FORMAT;
  }
  
  
  
  SimpleDateFormat sdf = new SimpleDateFormat(format);
  
  //获取传入的时间值
  Long time = new Date(sdf.parse(convertString).getTime()).getTime();
  
  
  //获取源时区时间相对的GMT时间
  Long sourceRelativelyGMT=time-TimeZone.getTimeZone(sourceTimeZone).getRawOffset();
  
  //GMT时间+目标时间时区的偏移量获取目标时间
  Long targetTime=sourceRelativelyGMT+TimeZone.getTimeZone(targetTimeZone).getRawOffset();
  
  
  date= new Date(targetTime);
  
  return date;
  
 }
 
 
 /**
  * Check empty string
  * <pre>
  *   null: true
  *   "": true
  *   " ":true
  * </>
  *
  * @param value
  * @return
  */
 public static boolean isEmpty(String value) {
  boolean emptyFlg = false;
  if (null == value || value.trim().length() <= 0) {
   emptyFlg = true;
  }
  return emptyFlg;
 }
}
 
 



posted on 2012-09-17 14:15 孤飞燕 阅读(6967) 评论(0)  编辑  收藏 所属分类: Java

只有注册用户登录后才能发表评论。


网站导航: