2016-12-14 79 views
0

已經有很多文章涉及這個主題,但是我將它們調整爲我的代碼,我無法找到合適的答案。日期格式丟失

try (BufferedReader br = new BufferedReader(new FileReader(path));) 
{   
     String line = ""; 

     Person tempPerson = null; 
     String dateFormat = "dd-MM-yyyy"; 
     SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); 
     Date tempBirthdayDate = null; 

     while ((line = br.readLine()) != null) 
     {    
      String[] splitFormat = line.split("/"); 
      for (String s : splitFormat) 
      { 
       String[] datamember = s.split(", "); 

       //Some more stuff... 

       tempBirthdayDate = sdf.parse(datamember[3]); 
       sdf.format(tempBirthdayDate); 
       sdf.applyPattern(dateFormat); 

       //Some more stuff... 

      } 

      tempPerson = new Person(...,...,...,tempBirthdayDate,...,...); 
     } 
} 

Person.java拷貝構造函數:

public Person(..., ..., ..., Date birthdayDate, ..., ...) 
{ 
    this.xxx = ...; 
    this.xxx = ...; 
    this.xxx = ...; 
    this.birthdayDate = birthdayDate; 
    this.xxx = adresse; 
    this.xxx = ...; 
} 

那些 「......」 只是把持有人縮短代碼。在源文件(.txt)中,日期與我在那裏定義的格式相同。但是,只要我在生日日誌中調用toString()方法,我就會得到如下結果。 05/26/1993: Wed May 26 00:00:00 CEST 1993.謝謝你的幫忙!

+0

你忘了提什麼是你想要的輸出? – user3437460

+0

您正在查找的字符串由'sdf.format(tempBirthdayDate)'返回。 'sdf.applyPattern(dateFormat)'是多餘的。 – shmosel

+0

你還期望什麼?閱讀您正在使用的方法的文檔 – njzk2

回答

0

Date對象的toString方法不受初始化的SimpleDateFormat的影響。

您需要創建一個自定義類擴展日期,並重寫toString方法

public class CustomDate extends Date { 
     ...... 
     @Override 
     public String toString(){ 
      return new SimpleDateFormat("dd-MM-yyyy").format(this); 
     } 
} 

親身構造

public Person(..., ..., ..., CustomDate birthdayDate, ..., ...) 
{ 
    this.xxx = ...; 
    this.xxx = ...; 
    this.xxx = ...; 
    this.birthdayDate = birthdayDate; 
    this.xxx = adresse; 
    this.xxx = ...; 
} 

您現在可以撥打birthdayDate的toString並獲得格式你想