2012-01-09 55 views
-1

我已經寫出了從給出正確結果的秒獲取日期格式的代碼。但是當我嘗試從日期格式獲取秒數時,我得到錯誤的結果。下面是代碼轉換爲給定日期格式的秒數

public class DateTimeFind 
{ 
    public static void main(String[] args){ 
     String seconds = "1325376000"; 
     DateTimeFind dtf = new DateTimeFind(); 
     // Displaying correct date from the given seconds 
     dtf.displayDate(seconds); 
     String date = "Sunday, January 1, 2012 12:00,AM"; 
     // Displaying wrong value of seconds from the given date. 
     dtf.displaySeconds(date); 
    } 

    private void displayDate(String seconds){ 
     long startEndSec = Long.parseLong(seconds); 
     SimpleDateFormat formatter = new SimpleDateFormat(
       "EEEE, MMMM d, yyyy h:mm,a", Locale.getDefault()); 
     formatter.setTimeZone(TimeZone.getTimeZone("UTC")); 
     String dateString = formatter.format(new Date(startEndSec * 1000L)); 
     System.out.println(dateString); 

    } 

    private void displaySeconds(String startEndDateTime){ 
     SimpleDateFormat sourceFormat = new SimpleDateFormat(
       "EEEE, MMMM dd, yyyy h:mm,a"); 
     long c = 0; 
     long c1 = 0; 
     try 
     { 
      Date t = (Date) sourceFormat.parse(startEndDateTime); 
      c = t.getTime()/1000; 
     } 
     catch(ParseException e) 
     { 
      e.printStackTrace(); 

     } 
     System.out.println(Long.toString(c)); 
    } 
} 
+0

你會得到什麼結果? – harto 2012-01-09 23:49:49

+0

我得到了結果1325356200 – Pradeep 2012-01-09 23:52:52

回答

1

你忘了設置在displaySeconds()方法所使用的SimpleDateFormat相同TimeZone。添加以下行:

sourceFormat.setTimeZone(TimeZone.getTimeZone("UTC")); 

無關到具體問題,用Locale.getDefault()治療日期格式的英語也並不完全正確。改爲使用Locale.ENGLISH,並將其添加到SimpleDateFormat的構造函數中,如displaySeconds()方法中所使用的。

+0

我明白了,thanq – Pradeep 2012-01-10 00:01:11