2016-12-14 9 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()メソッドを呼び出すとすぐに、birthdayDateのメソッドは次のような結果を得ます。 05/26/1993: Wed 5月26日00:00:00 CEST 1993.ありがとうございました!

+0

希望の出力は何ですか? – user3437460

+0

あなたが探している文字列は 'sdf.format(tempBirthdayDate)'によって返されます。そして 'sdf.applyPattern(dateFormat)'は冗長です。 – shmosel

+0

あなたは他に何を期待しますか?使用しているメソッドのドキュメントを読んでください – njzk2

答えて

0

DateオブジェクトのtoStringメソッドは、初期化したSimpleDateFormatの影響を受けません。

あなたは今birthdayDate上のtoStringを呼び出し、あなたが

をしたい形式を得ることができる人のコンストラクタで

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

をカスタムクラス拡張日付を作成し、toStringメソッド

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

をオーバーライドする必要があります