java - 转换给定时区的日期/时间 - java

我想将此 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?

是否可以:

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

最佳答案

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

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/

相关文章:

sql - 有哪些免费的 SQL 格式化工具?

c# - 您何时使用 StringBuilder.AppendLine/string.Format

javascript - 使用 Javascript 将 24 小时时间转换为 12 小时时间 w/

python - Python中用户友好的时间格式?

c# - 如何将 double 格式设置为四舍五入到最接近的美元的货币?

python - 如何自动格式化一些 Python 代码以正确格式化?

php - 如何在 PHP 中将数字格式化为美元金额

c# - 使用任意字符串向左或向右填充 string.format(不是 padleft 或 pad

c++ - 相当于 %02d 与 std::stringstream?

android - 在android中的编辑文本中格式化信用卡