2014-11-14 22 views
0

我必须解析像字符串dep但我没有办法事先知道时区和偏移量。我想分析该字符串,检索时区,并从GregoriaCalendar实例化的对象的偏移或避免转换为当地时区发生运行下面的代码:从SimpleDateFormat Java,GregorianCalendar,避免转换到本地时区

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(); 
    } 

} 

}

的输出是:

12/11/2014 CET time zone: Europe/Rome

我搜索日期,时区的SimpleTimeZone类文档中,但我没有发现任何对我的目的。 提前谢谢!

+0

所以你想忽略给定的时区并将日期视为绝对?你想要打印“13/11/2014”,而不是前一天? – markspace 2014-11-14 13:54:26

+0

不,我需要一种方法来从GregorianCalendar重建字符串“13/11/2014 GMT + 08:00”,而不使用静态初始化的任何字段。谢谢 – 2014-11-14 14:15:37

回答

0

这是我想出来的。请注意更改(注释行)。我也将日期本身改为与我的时区有正偏差,这样我可以重现您的原始错误。

基本上我没有看到反正这样做,除了分别处理时间和时区。您必须设置每个或您创建的Date对象将要转换为毫秒,并且它没有时区。

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(); 
     } 

    } 
} 
+0

谢谢!你确认什么变得我的信服,没有办法没有分裂... – 2014-11-14 14:39:04