I am writing a application where I want to convert a string "2011-07-17 08:05:50" to "Jul 17 08:05AM". Is there a direct way to do it in Java. I want both input and output in string. Please let me know if there is a way to do it directly. Thank you for your time and help.
-
have you tried download.oracle.com/javase/1.4.2/docs/api/java/text/… you can prase string in as date and then once date is formatted get string from it every task in java. Can not see any thing tricky in your question.Shahzeb– Shahzeb2011-07-17 00:35:23 +00:00Commented Jul 17, 2011 at 0:35
Add a comment
|
3 Answers
Use SimpleDateFormat,
public class Main {
public static void main(String[] args) throws Exception {
SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = sdfSource.parse("2011-07-17 08:05:50");
SimpleDateFormat sdfDestination = new SimpleDateFormat("MMM dd hh:mma");
System.out.println(sdfDestination.format(date));
}
}
Comments
Please let me know if there is a way to do it directly.
There is no way to do it directly. You have to parse the original string using a date parser, and then create a new one in the format you desire using a date formatter.
Your options are to use SimpleDateFormatter to parse and format, or use the equivalent JodaTime classes; e.g. DateTimeFormatter.
Comments
There's no "direct" way to do this. You have to use SimpleDateFormat to parse the first string into a Date object, than another to write it back out as the second string.
ie
Date date = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ).parse( inputString );
String outputString = new SimpleDateFormat( "MMM dd HH:mmaa" ).format( date );