[英]Does anyone know how extract my date string & change the format?
我的字符串中有一個有效的日期,如下所示:
String strDate = "Available on 03292013";
我想從strDate
字符串中提取日期並Available on 03/05/2015
日將其更改為Available on 03/05/2015
有誰知道我怎么能做到這一點?
您可以通過執行以下步驟來實現此目的:
[^0-9]
”從String中提取日期。 請在下面找到代碼,以便更清楚地了解實施情況。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.