1

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.

1

3 Answers 3

3

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));
  }
}

Reference.

Sign up to request clarification or add additional context in comments.

Comments

1

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

0

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 );

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.