Java,SimpleDataFormat中的GregorianCalendar,避免转换为本地时区
我必须解析字符串dep之类的东西,但我无法提前知道时区和偏移量。我希望解析字符串,从GregoriaCalendar实例化对象中检索时区和偏移量,或者避免转换为本地时区,就像运行以下代码时发生的那样:Java,SimpleDataFormat中的GregorianCalendar,避免转换为本地时区,java,date,timezone,gregorian-calendar,Java,Date,Timezone,Gregorian Calendar,我必须解析字符串dep之类的东西,但我无法提前知道时区和偏移量。我希望解析字符串,从GregoriaCalendar实例化对象中检索时区和偏移量,或者避免转换为本地时区,就像运行以下代码时发生的那样: public class Prova { public static void main(String[] args) { SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy z"); Strin
public class Prova {
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy z");
String dep = "13/11/2014 GMT+08:00";
GregorianCalendar gc1 = new GregorianCalendar();
try {
gc1.setTime(dateFormat.parse(dep));
System.out.println( dateFormat.format(gc1.getTime()) + " time zone: " + gc1.getTimeZone().getID());
} catch (ParseException | DatatypeConfigurationException e) {
e.printStackTrace();
}
}
}
输出为:
2014年11月12日CET时区:欧洲/罗马
我搜索了Date、TimeZone和SimpleTimeZone类文档,但没有找到任何有用的东西。
提前谢谢你 这是我想到的。请注意注释行中的更改。我还将日期本身更改为与时区的正偏移量,以便重现您最初的错误 基本上,我看不出有什么办法能做到这一点,除了把时间和时区分开处理。您必须设置每个日期,否则创建的日期对象将转换为毫秒,并且它没有时区
class Prova
{
public static void main( String[] args )
{
// SimpleDateFormat dateFormat = new SimpleDateFormat(
// "dd/MM/yyyy z" );
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd/MM/yyyy" );
String dep = "13/11/2014 GMT+12:00";
GregorianCalendar gc1 = new GregorianCalendar();
try {
String[] dateZone = dep.split( " " );
Date date = dateFormat.parse( dateZone[0] );
TimeZone tz = TimeZone.getTimeZone( dateZone[1] );
gc1.setTimeZone(tz);
gc1.setTime(date);
// gc1.setTime( dateFormat.parse( dep ) );
System.out.println( dateFormat.format( gc1.getTime() ) +
" time zone: " + gc1.getTimeZone().getID() );
} catch( ParseException e ) {
e.printStackTrace();
}
}
}
那么你想忽略给定的时区并将日期视为绝对日期?您希望打印2014年11月13日,而不是前一天?不,我需要一种方法从GregoriaCalendar中重建字符串13/11/2014 GMT+08:00,而不使用任何静态初始化的字段。谢谢