1

I'm trying to convert a String coming as "2014-11-04" from a Json Object, to "Tue,Nov 4" (I think it's "E, MMM d") but without sucess so far.

Here is the code of my last try:

private String convertDateString(String date) {

        SimpleDateFormat formatter = new SimpleDateFormat("E, MMM d");

        String convertedDate = formatter.format(date);


        return convertedDate;
    }

Thanks!

Makoto
  • 1,455
  • 4
  • 13
  • 17
  • possible duplicate of [Java string to date conversion](http://stackoverflow.com/questions/4216745/java-string-to-date-conversion) and [this](http://stackoverflow.com/q/4772425/642706) and many others. – Basil Bourque Nov 04 '14 at 07:31

3 Answers3

3

You can try as follows

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date=formatter.parse("2014-11-04");
                             formatter = new SimpleDateFormat("E, MMM d");
System.out.println(formatter.format(date));

You needs to convert String to Date first, Since current String is not other format.

Follow SimpleDateFormat, next time it will help you.

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
3
private static String convertDateString(String date) {

        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");

        SimpleDateFormat formatter = new SimpleDateFormat("E, MMM d");

        String convertedDate = null;
        try {
            convertedDate = formatter.format(f.parse(date));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return convertedDate;
    }

Input System.out.print(convertDateString("1990-10-11"));

Output Thu, Oct 11

Sunny
  • 14,522
  • 15
  • 84
  • 129
1

To change date from one format to another,first convert original formatted String to date and then format it to target format. try this

private String convertDateString(String dateInString) {
    SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat targetFormat = new SimpleDateFormat("E, MMM d");
    Date date = originalFormat.parse(dateInString);
    return targetFormat.format(date);
}
Giru Bhai
  • 14,370
  • 5
  • 46
  • 74