2012-04-20 138 views
0

我附上的代码。在这段代码中,我使用了一个字符串,它是一个来自平面文本文件的日期。它由AM/PM(12小时格式)组成。当我解析它时,它不能以24小时格式解析。我想要时间差b/w当前时间和文件中的字符串。并且由于AM/PM,它不能以24小时格式转换。因此无论是PM还是AM都显示相同的时差。所以,如果你有,请告诉我任何富有成效的建议。我会非常感谢你们。解析字符串日期和时间,但没有得到适当的解析

公共类铸件{

/** 
* @param args 
*/ 
    static FileReader fw; 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     try{ 
      fw = new FileReader("E://796F_log.txt"); 
      BufferedReader pw =new BufferedReader(fw); 
      String last_Line_From_File="" ; 

      for (String message = pw.readLine(); message != null ; message = pw.readLine()) { 
        last_Line_From_File = message; 
      } 

      String[] array_Of_Data = last_Line_From_File.split("\\s") ; 
      String time = array_Of_Data[0]+" "+array_Of_Data[1]+" "+array_Of_Data[2] ; 

      System.out.println(time); 
      DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a"); 
      Calendar cal = Calendar.getInstance(); 
      String current_time = dateFormat.format(cal.getTime()); 

      Date d1 = dateFormat.parse(time); 
      Date d2 = dateFormat.parse(current_time); 



      long total_time = d2.getTime()-d1.getTime(); 
      total_time /= 1000 ; 

      System.out.println("current time "+d2.getHours()+":"+d2.getMinutes()+":"+d2.getSeconds()+"\n"+d1.getHours()+":"+d1.getMinutes()+":"+d1.getSeconds()); 
      if(total_time <= 500) 
      { 
       System.out.println("working "+total_time); 
      } 
      else 
       System.out.println("nt working "+total_time); 

     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      System.out.println("did the smart thing or dumb thing"); 
     } catch (ParseException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     }finally 
     { 
      try { 
       fw.close(); 

      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
       System.out.println("we did attempt closing"); 

      } 

     } 
    } 

}

+0

请提供输入和输出字符串....以便我们可以跟踪错误.... – aProgrammer 2012-04-20 06:25:56

+0

快速提示:您的问题会更清晰*没有*所有的文件处理代码,但*带* a输入样本。您也不应该在'日期'内使用弃用的方法。 – 2012-04-20 06:27:17

回答

3

的问题是您的格式:

"MM/dd/yyyy HH:mm:ss a" 

HH这里指24小时值。因此,它预计晚上7点会有“19”。这几乎是总是在同一个格式字符串中包含“HH”和“a”(AM/PM指示符)是错误的。

你可能想要么

"MM/dd/yyyy hh:mm:ss a" 

"MM/dd/yyyy h:mm:ss a" 

取决于你是否把事情就像 “上午7时00分○○秒” 或 “7:00:00点”。顺便说一句,如果你正在做大量的日期/时间工作,我推荐使用Joda Time而不是Date/Calendar

+0

thnx很多我被困在这个问题...最后3天... thnx一吨 – 2012-04-20 09:28:47