GMT 时间转换问题

转自http://www.exampledepot.com/egs/java.util/GetTimeOtherZone2.html

There is a convenient setTimeZone() method in the Calendar object. However, it doesn't always return the correct results when used after a calendar field is set. This example demonstrates a more reliable way to convert a specific time from one time zone to another. It involves creating two Calendar instances and transfering the UTC (Coordinate Universal Time) from one to the other. The UTC is a representation of time and date that is independent of time zones.

// Given a local time of 10am, get the time in Japan
// Create a Calendar object with the local time zone
Calendar local = new GregorianCalendar();
local.set(Calendar.HOUR_OF_DAY, 10);               // 0..23
local.set(Calendar.MINUTE, 0);
local.set(Calendar.SECOND, 0);

// Create an instance using Japan's time zone and set it with the local UTC
Calendar japanCal = new GregorianCalendar(TimeZone.getTimeZone("Japan"));
japanCal.setTimeInMillis(local.getTimeInMillis());

// Get the foreign time
int hour = japanCal.get(Calendar.HOUR);            // 3
int minutes = japanCal.get(Calendar.MINUTE);       // 0
int seconds = japanCal.get(Calendar.SECOND);       // 0
boolean am = japanCal.get(Calendar.AM_PM) == Calendar.AM; //true


// Given a time of 10am in Japan, get the local time
japanCal = new GregorianCalendar(TimeZone.getTimeZone("Japan"));
japanCal.set(Calendar.HOUR_OF_DAY, 10);            // 0..23
japanCal.set(Calendar.MINUTE, 0);
japanCal.set(Calendar.SECOND, 0);

// Create a Calendar object with the local time zone and set
// the UTC from japanCal
local = new GregorianCalendar();
local.setTimeInMillis(japanCal.getTimeInMillis());

// Get the time in the local time zone
hour = local.get(Calendar.HOUR);                   // 5
minutes = local.get(Calendar.MINUTE);              // 0
seconds = local.get(Calendar.SECOND);              // 0
am = local.get(Calendar.AM_PM) == Calendar.AM;     // false

Calendar.setDate() always doesn't work , it converts the date to the one in the Calendar timezone

you should set each field with a absolute value like local.set(Calendar.HOUR_OF_DAY, 10);               // 0..23
local.set(Calendar.MINUTE, 0);
local.set(Calendar.SECOND, 0);

the value you use for hour,minute,second can be obtained from a local canlendar or date object.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值