-2

I have a string that contains a date like so:

String startTime = "2014-10-11T17:00:41+0000"

I am trying to reformat that string so that it reads like so instead:

Oct 11, 2014 5:00 PM 
M. A. Kishawy
  • 5,001
  • 11
  • 47
  • 72
Gchorba
  • 301
  • 2
  • 13
  • 1
    Using Java's Formatter: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html it's an option at least. String.format() may be able to do what you need but it doesn't give the efficiencies of Formatter (via http://stackoverflow.com/questions/513600/should-i-use-javas-string-format-if-performance-is-important) – zgc7009 Oct 01 '14 at 20:56
  • Dare I suggest using jodatime? – Kristy Welsh Oct 01 '14 at 22:11

2 Answers2

1

Use SimpleDateFormat for parse input string and represent in new format: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Ex.:

SimpleDateFormat sdfmtIn = new SimpleDateFormat("dd/MM/yy");
SimpleDateFormat sdfmtOut= new SimpleDateFormat("dd-MMM-yyyy");
java.util.Date date = sdfmtIn.parse(strInput);
String strOutput = sdfmtOut.format(date);
nister
  • 171
  • 6
1

Since Date objects do not keep time zone information, you need to specifically set the time zone offset of original date to the target formatter. Here is the complete code for transforming from one format to another while maintaining the time zone offset (+0000 in your case). More information on TimeZone class here and on how to build a proper date and time pattern string for your requirement here.

try {
    DateFormat originalFormat = new SimpleDateFormat(
            "yyyy-MM-dd'T'HH:mm:ssZ", Locale.ENGLISH);
    DateFormat targetFormat = new SimpleDateFormat(
            "MMM dd, yyyy K:mm a", Locale.ENGLISH);
    targetFormat.setTimeZone(TimeZone.getTimeZone("GMT+0000"));
    Date date = originalFormat.parse("2014-10-11T17:00:41+0000");
    String formattedDate = targetFormat.format(date);

    System.out.println(formattedDate);
} catch (ParseException e) {
    e.printStackTrace();
}

Output: Oct 11, 2014 5:00 PM

Voicu
  • 16,921
  • 10
  • 60
  • 69