Reputation: 67
I am writing a converter method that would parse an xml string data to java objects. But i am not able to parse dates to date objects.
How to format this date string "2013-08-26T12:00:00.000"
in the following way: "2013-08-26 12:00:00"
to Date object in java?
Note: The input can be of multiple date format like - "2013-08-26T12:00:00.000"
or "2013-08-26T12:00:00.000Z"
. The input dates are of variable formats.
Edited to add the below code snippet. Here is what I tried to do.
public Object fromString(String str) {
DateFormat dateFormat = DateFormat.getDateInstance();
try {
Date date = dateFormat.parse(str);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
}
Upvotes: 0
Views: 145
Reputation: 44071
In order to process XML-date-time-strings which are allowed to be of variable precision (sometimes leaving out second- or fraction-part or timezone-offset) the use of SimpleDateFormat
is not a good option because then you would only have one pattern. Not flexible.
Alternative for XML:
String xml = "2013-08-26T12:00:00.000"; // maybe optionally with additional timezone offset
javax.xml.datatype.DatatypeFactory factory = javax.xml.datatype.DatatypeFactory.newInstance();
XMLGregorianCalendar xmlGregCal = factory.newXMLGregorianCalendar(xml);
java.util.Date d = xmlGregCal.toGregorianCalendar().getTime();
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String output = outputFormat.format(d);
Watch also out for some overloaded methods to change the timezone settings for parsing and formatting - see the javadoc.
Upvotes: 1
Reputation: 8068
You may try this:
public static void main(String[] args) throws Exception {
String original = "2013-08-26T12:00:00.000";
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S").parse(original);
String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
System.out.printf("Before: %s\nAfter: %s\n", original, format);
}
OUTPUT:
Before: 2013-08-26T12:00:00.000
After: 2013-08-26 12:00:00
Upvotes: 0
Reputation: 116
You should google these things first. Here you go:
public static void main(String[] args) {
String inFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS";
String outFormat = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(inFormat);
try {
Date d = sdf.parse("2013-08-26T12:00:00.000");
sdf.applyPattern(outFormat);
System.out.println(sdf.format(d));
} catch (ParseException e) {
// handle appropriately
e.printStackTrace();
}
}
Upvotes: 3
Reputation: 3353
You can parse any Date-like string to Date object (as long as the the string represents a valid date) using http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
There is no point in re-formatting the String.
Upvotes: 2