//Get the current time zone
public static int getTimeZone() { Date date=new Date(); //Get the local time Calendar cal = Calendar.getInstance(); //Get the time offset int offset = cal.get(Calendar. ZONE_OFFSET)/(1000*60*60); //Get the daylight saving time difference int dstOffset=cal.get(Calendar.DST_OFFSET)/(1000*60*60); //Deduct these variables from the local time to get UTC time cal.add(Calendar.MILLISECOND, -(offset+dstOffset)); cal.add(Calendar.HOUR, -(offset + dstOffset)); Long timeStampUTC = cal.getTimeInMillis(); Long timeStamp = date.getTime() ; Long timeZone = (timeStamp - timeStampUTC) / (1000 * 3600);return timeZone.intValue();
}
Demo of world time zone conversion
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import com.su.test.R;
public class MainActivity extends Activity {
/**
* 测试时请手动切换手机的时差设置
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
initListeners();
initValues();
}
private void initViews() {
// TODO Auto-generated method stub
// 例如:北京时间:2014-11-28 11:12:45 转化美国洛杉矶应为 2014-11-27 19:12:45
Log.d("test", "北京时间转化美国洛杉矶时间:" + getZoneTime("2014-11-28 11:12:45", "yyyy-MM-dd HH:mm:ss"));
//测试结果 D/test(23630): 北京时间转化美国洛杉矶时间:2014-11-27 19:12:45 与预期一致
// 例如:北京时间:2014-11-28 11:13:42 转化英国伦敦应为 2014-11-28 03:13:42
Log.d("test", "北京时间转化英国伦敦时间:" + getZoneTime("2014-11-28 11:13:42", "yyyy-MM-dd HH:mm:ss"));
//测试结果 D/test(24005): 北京时间转化英国伦敦时间:2014-11-28 03:13:42 与预期一致
// 例如:北京时间:2014-11-28 11:14:00 转化华宝客户-肯尼亚时间应为 2014-11-28 06:13:59
Log.d("test", "北京时间转化肯尼亚(内罗毕)时间:" + getZoneTime("2014-11-28 11:14:00", "yyyy-MM-dd HH:mm:ss"));
//测试结果 D/test(24553): 北京时间转化肯尼亚(内罗毕)时间:2014-11-28 06:14:00 与预期一致
// 结论: getZoneTime(String strDate, String formatStr) 没问题
}
private void initListeners() {
// TODO Auto-generated method stub
}
private void initValues() {
// TODO Auto-generated method stub
}
/**
* 把北京时间转换成当前时区上的时间
*
* @param strDate
* @param formatStr
* @return
*/
public static String getZoneTime(String strDate, String formatStr) {
long defZone = 8 * 60 * 60 * 1000;
Date date = StringToDate(strDate, formatStr);
TimeZone zone = TimeZone.getDefault();
return DateToString(new Date(date.getTime() - defZone + zone.getRawOffset()), formatStr);
}
/**
* 字符串转日期
*
* @param dateStr
* @param formatStr格式
* (如:yyyy-MM-dd HH:mm:ss)
* @return
*/
public static Date StringToDate(String dateStr, String formatStr) {
DateFormat dd = new SimpleDateFormat(formatStr);
Date date = null;
try {
date = dd.parse(dateStr);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* 日期转获取字符串
*
* @param date日期
* @param format格式
* (如:yyyy-MM-dd HH:mm:ss)
*
* @return
*/
public static String DateToString(Date date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
}