次のように、文字列に有効な日付があります。
String strDate = "Available on 03292013";
strDate
文字列から日付を抽出して変更したいAvailable on 03/05/2015
どうすればこれを達成できるか知っている人はいますか?
これは、次の手順を実行することで実現できます。
[^0-9]
" を使用して文字列から日付を抽出します。実装をより明確にするために、以下のコードを見つけてください。
package com.stackoverflow.works;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author sarath_sivan
*/
public class DateFormatHelper {
private static final String DD_MM_YYYY = "MMddyyyy";
private static final String DD_SLASH_MM_SLASH_YYYY = "MM/dd/yyyy";
public static void main(String[] args) {
DateFormatHelper dateFormatHelper = new DateFormatHelper();
dateFormatHelper.run();
}
public void run() {
String strDate = "Available on 03292013";
System.out.println("Input Date: " + strDate);
strDate = DateFormatHelper.getDate(strDate);
strDate = "Available on " + DateFormatHelper.formatDate(strDate);
System.out.println("Formatted Date: " + strDate);
}
public static String formatDate(String strDate) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DD_MM_YYYY);
Date date;
try {
date = simpleDateFormat.parse(strDate);
simpleDateFormat = new SimpleDateFormat(DD_SLASH_MM_SLASH_YYYY);
strDate = simpleDateFormat.format(date);
} catch (ParseException parseException) {
parseException.printStackTrace();
}
return strDate;
}
public static String getDate(String strDate) {
return strDate.replaceAll("[^0-9]", "");
}
}
出力:
Input Date: Available on 03292013
Formatted Date: Available on 03/29/2013
お役に立てれば...
このシンプルでエレガントなアプローチを試してください。
DateFormat dateParser = new SimpleDateFormat("'Available on 'MMddyyyy");
DateFormat dateFormatter = new SimpleDateFormat("'Available on 'dd/MM/yyyy");
String strDate = "Available on 03292013";
Date date = dateParser.parse(strDate);
System.out.println(dateFormatter.format(date));
これはあなたが望むことをするはずです。String
実際に含まれているもの (この場合は日付) を考慮せずに を操作しているだけであることに注意してください。
String strDate = "Available on 03292013";
String newStr = strDate.substring(0, 15) + "/"
+ strDate.substring(15, 17) + "/" + strDate.substring(17);
System.out.println(newStr);
結果:
Available on 03/29/2013