转换给定时区的日期/时间 - java [英] Convert Date/Time for given Timezone - java

查看:28
本文介绍了转换给定时区的日期/时间 - java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将此 GMT 时间戳转换为 GMT+13:

I want to convert this GMT time stamp to GMT+13:

2011-10-06 03:35:05

我尝试了大约 100 种不同的 DateFormat、TimeZone、Date、GregorianCalendar 等组合来尝试完成这项非常基本的任务.

I have tried about 100 different combinations of DateFormat, TimeZone, Date, GregorianCalendar etc. to try to do this VERY basic task.

这段代码为当前时间做了我想要的:

This code does what I want for the CURRENT TIME:

Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT"));

DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");    
formatter.setTimeZone(TimeZone.getTimeZone("GMT+13"));  

String newZealandTime = formatter.format(calendar.getTime());

但我想要的是设置时间而不是使用当前时间.

But what I want is to set the time rather than using the current time.

我发现任何时候我都尝试像这样设置时间:

I found that anytime I try to set the time like this:

calendar.setTime(new Date(1317816735000L));

使用本地机器的时区.这是为什么?我知道当new Date()"返回 UTC+0 时间时,为什么当您以毫秒为单位设置时间时,它不再假设时间为 UTC?

the local machine's TimeZone is used. Why is that? I know that when "new Date()" returns UTC+0 time so why when you set the Time in milliseconds does it no longer assume the time is in UTC?

是否可以:

  1. 在对象上设置时间(日历/日期/时间戳)
  2. (可能)设置初始时间戳的 TimeZone (calendar.setTimeZone(...))
  3. 使用新的 TimeZone 格式化时间戳 (formatter.setTimeZone(...)))
  4. 返回带有新时区时间的字符串.(formatter.format(calendar.getTime()))

在此先感谢您的帮助:D

Thanks in advance for any help :D

推荐答案

对我来说,最简单的方法是:

Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

//Here you say to java the initial timezone. This is the secret
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
//Will print in UTC
System.out.println(sdf.format(calendar.getTime()));    

//Here you set to your timezone
sdf.setTimeZone(TimeZone.getDefault());
//Will print on your default Timezone
System.out.println(sdf.format(calendar.getTime()));

这篇关于转换给定时区的日期/时间 - java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆