Converting Date String To Another String
How can I convert from '2014-10-13T10:41:22.863+08:00' into '2014-10-13 10:41'? I have failed to do so: String date = '2014-10-13T10:41:22.863+8:00'; SimpleDateFormat dateFormat =
Solution 1:
Try this way,hope this will help you to solve your problem.
The Z at the end is usually the timezone offset. If you you don't need it maybe you can drop it on both sides.
SimpleDateFormatdf1=newSimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
SimpleDateFormatdf2=newSimpleDateFormat("yyyy-MM-dd HH:mm");
try{
Dated= df1.parse("2014-10-13T10:41:22.863+8:00");
System.out.println("new date format " + df2.format(d));
}catch(Exception e){
e.printStackTrace();
}
Solution 2:
If you don't need to do some operation/manipulation on the Date
before printing it in correct format, then you can just directly transform the string into yyyy-MM-dd HH:mm
with this:
String date = "2014-10-13T10:41:22.863+8:00";
date = date.substring(0, 16); // 2014-10-13T10:41, remove value after minutes
date = date.replace("T", " "); // 2014-10-1310:41, replace the 'T' character
System.out.println(date); // 2014-10-1310:41
Else, if you want to parse it beforehand, then change the pattern to yyyy-MM-dd'T'HH:mm
(note the additional of string constant 'T'
).
Stringdate="2014-10-13T10:41:22.863+8:00";
// parse the String to DateSimpleDateFormatsourceFormat=newSimpleDateFormat("yyyy-MM-dd'T'HH:mm");
DatedateTime=null;
try {
dateTime = sourceFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(dateTime.toString()); // Mon Oct 13 10:41:00 SGT 2014// print the Date in expected formatSimpleDateFormattargetFormat=newSimpleDateFormat("yyyy-MM-dd HH:mm");
System.out.println(targetFormat.format(dateTime)); // 2014-10-13 10:41
The reason you got ParseException
is because the format you use to parse (yyyy-MM-dd HH:mm
) is not the same as the source (yyyy-MM-dd'T'HH:mm ...
). Your SimpleDateFormatter
expected whitespace instead of character 'T' after the date.
Post a Comment for "Converting Date String To Another String"