我想将此 GMT 时间戳转换为 GMT+13:
2011-10-06 03:35:05
我已经尝试了大约 100 种不同的 DateFormat、TimeZone、Date、GregorianCalendar 等组合来尝试完成这项非常基本的任务。
此代码在当前时间执行我想要的操作:
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());
但我想要的是设置时间而不是使用当前时间。
我发现任何时候我都尝试这样设置时间:
calendar.setTime(new Date(1317816735000L));
使用本地机器的时区。这是为什么?我知道当“new Date()”返回 UTC+0 时间时,为什么当您以毫秒为单位设置时间时,它不再假定时间为 UTC?
是否可以:
最佳答案
对我来说,最简单的方法是:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
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()));
https://stackoverflow.com/questions/7670355/