Java日期到时区的转换不起作用 [英] Java date conversion to timezone not working
问题描述
在Java中,我从英国下载时间,现在在多伦多,我想获取时区并将转换后的日期对象更改为该时区,但是它不起作用.
In java, I download a time from the UK and I am in toronto, I want to get the timezone and change the converted date object to it, but it's not working.
public static Date getDateFromSQLDate(String sqldate) {
try {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date = (Date) formatter.parse(sqldate);
TimeZone tz = TimeZone.getDefault();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.setTimeZone(tz);
return calendar.getTime();
//return date;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
有人知道怎么了吗?
谢谢
推荐答案
DateFormat使用系统的默认时区,最可能是多伦多.您需要做的是:
DateFormat uses the system's default timezone, which most likely to be Toronto. What you need to do is:
DateFormat formatter = ...
formatter.setTimeZone(TimeZone.getTimeZone("Europe/London"));
Date date = (Date) formatter.parse(sqldate);
return date;
或适用于您的英国"时间的时区标识符.您可以在此处查看受支持的标识符名称列表: http://en.wikipedia.org/wiki/List_of_tz_database_time_zones
Or whichever time zone identifier applicable to your "UK" time. You can see the list of supported identifier names here: http://en.wikipedia.org/wiki/List_of_tz_database_time_zones
请记住,Date对象(或java.sql.Date)中从未存储任何时区信息.说您要转换Date对象的时区只是没有任何意义,因为您不能这样做.
Keep in mind that the Date object (or java.sql.Date) never has any timezone information stored in it. Saying you want to convert a timezone of a Date object just doesn't make any sense because you can't.
您可以做的是设置解析时区,或设置Date对象的格式.
What you can do is to set the timezone from which you parse, or format the Date object.
这篇关于Java日期到时区的转换不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!