我有一个要求,考虑到夏令时,我必须将时区从 UTC 转换为特定时区,反之亦然。我正在java.util.TimeZone为它使用类。现在,问题是时区有数百个无法向用户显示的 ID。
作为现在的解决方法,我们决定首先列出国家/地区列表并列出所选国家/地区的时区。我不能够得到TimeZone一个ISO国家代码。
这是我目前用来转换时区的代码,
Timestamp convertedTime = null;
try{
System.out.println("timezone: "+timeZone +", timestamp: "+timeStamp);
Locale locale = Locale.ENGLISH;
TimeZone destTimeZone = TimeZone.getTimeZone(timeZone);// TimeZone.getDefault();
System.out.println("Source timezone: "+destTimeZone);
DateFormat formatter = DateFormat.getDateTimeInstance(
DateFormat.DEFAULT,
DateFormat.DEFAULT,
locale);
formatter.setTimeZone(destTimeZone);
Date date = new Date(timeStamp.getTime());
System.out.println(formatter.format(date));
convertedTime = new Timestamp(date.getTime());
/*long sixMonths = 150L * 24 * 3600 * 1000;
Date inSixMonths = new Date(timeStamp.getTime() + sixMonths);
System.out.println("After 6 months: "+formatter.format(inSixMonths));
Run Code Online (Sandbox Code Playgroud)
我需要找出要在给定国家/地区 ISO 代码的上述代码中使用的时区 ID。
更新:尝试了很多东西,下面的代码让我得到了 148 个条目(仍然很大)的时区列表。任何人都可以帮我缩短它。或者,建议一些其他方法来缩短时区列表或获取某个国家/地区的时区, …
我试图将格式化的日期字符串转换为Date对象.日期字符串格式化为某个其他时区.
当我这样做时sdf.parse(String),返回我的系统日期对象.
代码如下,
static Date convertGMTTime(String timeZone, long longDate){
Date convertedTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try{
Date date = new Date(longDate);
System.out.println("timezone: "+timeZone +", timestamp: "+date);
Locale locale = Locale.ENGLISH;
TimeZone destTimeZone = TimeZone.getTimeZone(timeZone);// TimeZone.getDefault();
System.out.println("Source timezone: "+destTimeZone);
/* DateFormat formatter = DateFormat.getDateTimeInstance(
DateFormat.DEFAULT,
DateFormat.DEFAULT,
locale);
formatter.setTimeZone(destTimeZone);*/
sdf.setTimeZone(destTimeZone);
String convertedDateStr = sdf.format(date);
System.out.println("convertedDateStr: "+convertedDateStr);
convertedTime = sdf.parse(convertedDateStr);
System.out.println("convertedTime: "+convertedTime + "sdf: "+sdf.getTimeZone());
}catch(Exception e){
e.printStackTrace();
}
return convertedTime;
}
Run Code Online (Sandbox Code Playgroud)
如果有人能提供帮助并指出我哪里出错,我将不胜感激.提前致谢.
输出:
时区:Atlantic/Cape_Verde,时间戳:Tue Jun 26 …