I'm happy to live!

Develop with pleasure!

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  39 随笔 :: 2 文章 :: 31 评论 :: 0 Trackbacks
    在我的项目中,用户会选择自已的时区,所以显示的时间都是根据用户选择的时区来显示时间的,而时间我存入数据库时我打算是转成格林威治时间,然后从库里取出时间后又根据用户的选择来转成对应时区的时间
但现在却碰到一些问题,如何将对应时区的时间转成格林威治时间呢?

以下是我的部分代码:
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG,
                DateFormat.LONG);
        Calendar cal 
= Calendar.getInstance();

        TimeZone tz 
= TimeZone.getTimeZone("America/Los_Angeles");

        df.setTimeZone(tz);
        String time 
= df.format(new Date());
        System.out.println(time);
        Date date 
= df.parse(time, new ParsePosition(0));
        System.out.println(date);
为何df.parse()后返回的date又成了当前系统的时间了啊,我如何把当前用户时区的时间转换成格林威治时间呢,谢谢牛人们?
posted on 2011-01-05 07:31 Norsor 阅读(1672) 评论(3)  编辑  收藏 所属分类: programme

评论

# re: 关于时间的一些疑问? 2011-01-05 11:41 何杨
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("London"));

int hour12 = cal.get(Calendar.HOUR); // 0..11
int minutes = cal.get(Calendar.MINUTE); // 0..59
int seconds = cal.get(Calendar.SECOND); // 0..59

System.out.println(hour12+":"+minutes+":"+seconds);

以上是Java Almanac 1.4中找到的。  回复  更多评论
  

# re: 关于时间的一些疑问? 2011-01-05 20:59 Rene
因为你只用了一个DateFormat,等于是在同一个时区内转换。

format: 把Date对象基于DateFormat时区转换成字符串
parse: 把字符串基于DateFormat时区转换成当前时区的Date对象
比如:用户地区为中国(GMT+8),DateFormat时区为GMT,时间字符串:2011/01/05 12:00:00
parse后的结果是 Wed Jan 05 13:00:00 CET 2011

SimpleDateFormat dbFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dbFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
dbFormat.format(localDate);
可以获得当前时间的GMT时区日期字符串。
如果要获得Date对象,要基于用户时区做parse转换

完整例子:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class CalendarTest {
public static void main (String[] args) {
SimpleDateFormat localFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
SimpleDateFormat dbFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dbFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

Date localDate = new Date();
System.out.println("Local: "+localDate);

// Solution one to get a date object
try {
Date GMTDate = localFormat.parse(dbFormat.format(localDate));
System.out.println("1. GMT: "+GMTDate);
} catch (ParseException e) {
e.printStackTrace();
}

//Solution two to get a simple String
System.out.println("2. GMT: "+dbFormat.format(localDate));
}
}  回复  更多评论
  

# re: 关于时间的一些疑问? 2011-01-05 21:07 Rene
@何杨
建议使用"GMT",用London的话有夏令时问题,夏令时期间就是GMT+1了  回复  更多评论
  


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


网站导航: