2012-03-11 9 views
-1

Stringを解析して月の日にアクセスしてDateを作成すると、間違った値が返されます。フォーマットされた文字列から月の日を取得するには?

Date datearr = null; 
DateFormat df1 = new SimpleDateFormat("dd-MM-yyyy"); 
String dataa = "17-03-2012"; 
try { 
    datearr = df1.parse(dataa); 
} catch (ParseException e) { 
    Toast.makeText(this, "err", 1000).show(); 
} 

int DPDMonth = datearr.getMonth() + 1; 
int DPDDay = datearr.getDay(); 
int DPDYear = datearr.getYear() + 1900; 

System.out.println(Integer.toString(DPDDay)+"-"+Integer.toString(DPDMonth)+"-"+Integer.toString(DPDYear)); 

なぜ私は0代わりの17を得るのですか?

03-11 10:24:44.286: I/System.out(2978): 0-3-2012 
+3

使用しているメソッドのjavadocを読んで、推奨されていない警告に気付き、ドキュメントが示唆しているコードに置き換えてください。また、 'datearr.getMonth()'というコードが実行されたときに、ParseExceptionが発生した場合にどうなるか考えてみてください。 –

+2

そして、変数の命名規則に関連するJavaの規約を使用してください...コードを読み込み、変数をクラスとしてハイライト表示しようとするのは非常に面倒です。 – Marcelo

+0

申し訳ありませんが、ここに私の最初の投稿です。 –

答えて

1

ここで、インクルードはもう非推奨メソッドを使用していないスニペットだ問題を命名修正し、出力を簡素化します。サードパーティのライブラリ、Joda-Time 2.3を使用しているとき

Date datearr = null; 
    DateFormat df1 = new SimpleDateFormat("dd-MM-yyyy"); 
    String dataa = "17-03-2012"; 
    try { 
     datearr = df1.parse(dataa); 
    } catch (ParseException e) { 
     Toast.makeText(this, "err", 1000).show(); 
     return; // do not continue in case of a parse problem!! 
    } 

    // "convert" the Date instance to a Calendar 
    Calendar cal = Calendar.getInstance(); 
    cal.setTime(datearr); 

    // use the Calendar the get the fields 
    int dPDMonth = cal.get(Calendar.MONTH)+1; 
    int dPDDay = cal.get(Calendar.DAY_OF_MONTH); 
    int dPDYear = cal.get(Calendar.YEAR); 

    // simplified output - no need to create strings 
    System.out.println(dPDDay+"-"+dPDMonth+"-"+dPDYear); 
0

あなたは日を返す)

int DPDDay = datearr.getDate(); 

getDayを(使用する必要があります週に

+0

Zoon Nooz、thx!申し訳ありませんが、皆私の不注意のため –

0

この種の仕事は非常に簡単です。

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so. 
// import org.joda.time.*; 
// import org.joda.time.format.*; 

String dateString = "17-03-2012"; 

DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-yyyy"); 
DateTime dateTime = formatter.parseDateTime(dateString).withTimeAtStartOfDay(); 

int dayOfMonth = dateTime.getDayOfMonth(); 
関連する問題