Reputation: 33
I have a valid date in my String like this:
String strDate = "Available on 03292013";
I want to extract the date from the strDate
String & change it to Available on 03/05/2015
Does anyone know how can I achieve this?
Upvotes: 1
Views: 180
Reputation: 422
This should do what you want. Note that I'm just manipulating the String
without any regards for what it actually contains (a date in this case).
String strDate = "Available on 03292013";
String newStr = strDate.substring(0, 15) + "/"
+ strDate.substring(15, 17) + "/" + strDate.substring(17);
System.out.println(newStr);
Result:
Available on 03/29/2013
Upvotes: 0
Reputation: 8032
You can achieve this by doing the following steps:
[^0-9]
" to extract the date from your String.Please find below code for better clarity on the implementation.
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]", "");
}
}
Output:
Input Date: Available on 03292013
Formatted Date: Available on 03/29/2013
Hope this helps...
Upvotes: 2
Reputation: 4346
Try this simple and elegant approach.
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));
Upvotes: 1