私のデータベースでは、2011-11-30(yyyy/mm/dd)のような開始日と40日のような継続日数を取得していますが、どうすれば日数を計算して新しい日付形式mm/dd/yyyyを取得できますか?
どなたか教えてください。
ありがとうございます。
このようなことを試してみてはいかがでしょうか。
String dt = "2012-01-04"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(dt));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DATE, 40); // number of days to add, can also use Calendar.DAY_OF_MONTH in place of Calendar.DATE
SimpleDateFormat sdf1 = new SimpleDateFormat("MM-dd-yyyy");
String output = sdf1.format(c.getTime());
ステップ1 指定した文字列からCalendarインスタンスを取得する。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dateInString));
ステップ2 add()
を使用して、カレンダーに日数を追加する。
c.add(Calendar.DATE, 40);
ステップ-3 dtaeを結果の日付フォーマットに変換する。
sdf = new SimpleDateFormat("MM/dd/yyyy");
Date resultdate = new Date(c.getTimeInMillis());
dateInString = sdf.format(resultdate);
**ソースコード
String dateInString = "2011-11-30"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dateInString));
c.add(Calendar.DATE, 40);
sdf = new SimpleDateFormat("MM/dd/yyyy");
Date resultdate = new Date(c.getTimeInMillis());
dateInString = sdf.format(resultdate);
System.out.println("String date:"+dateInString);
Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
// display the current date
String CurrentDate = mYear + "/" + mMonth + "/" + mDay;
String dateInString = CurrentDate; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
c = Calendar.getInstance();
try {
c.setTime(sdf.parse(dateInString));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.add(Calendar.DATE, 7656);//insert the number of days you want to be added to the current date
sdf = new SimpleDateFormat("dd/MM/yyyy");
Date resultdate = new Date(c.getTimeInMillis());
dateInString = sdf.format(resultdate);
//Display the Result in the Edit Text or Text View your Choice
EditText etDOR = (EditText)findViewById(R.id.etDateOfReturn);
etDOR.setText(dateInString);