-10

i have date format in 02/20/2016 i have to convert it in to Feb 26, 2016 please suggest me how to convert it in this format .

Research Development
  • 884
  • 1
  • 19
  • 39

1 Answers1

1
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {

  public static void main(String[] args) throws ParseException {

    String theInDate = "2/20/2016";

    String theInFormat = "MM/dd/yyyy";
    String theOutFormat = "MMM dd, yyyy";

    final SimpleDateFormat theSdfInputFormatter = new SimpleDateFormat(theInFormat);
    final SimpleDateFormat theSdfOutputFormatter = new SimpleDateFormat(theOutFormat);

    final Date theDate = theSdfInputFormatter.parse(theInDate);

    final String theDateText = theSdfOutputFormatter.format(theDate);

    System.out.println(theDateText);

    }
}

You might wantto check the setLinient(true) functionality on the date parser as well.

And with the new Date API

    String theInDate = "2/20/2016";

    String theInFormat = "M/d/yyyy";
    String theOutFormat = "MMM dd, yyyy";

    final DateTimeFormatter theSdfInputFormatter = DateTimeFormatter.ofPattern( theInFormat );
    final DateTimeFormatter theSdfOutputFormatter = DateTimeFormatter.ofPattern(theOutFormat);

    final LocalDate theDate = LocalDate.from( theSdfInputFormatter.parse( theInDate ) );

    final String theDateText = theSdfOutputFormatter.format(theDate);

    System.out.println(theDateText);

Be aware of thread safety. take a look at the javadoc. This solution works for Java. For Android, as tagged, it should be quite similar. And even though this is a duplicate answer I hope it helps someone to solve an issue very fast and get an understanding how it works for further self study.

Dirk Schumacher
  • 1,479
  • 19
  • 37
  • Answering obvious duplicate Questions is not helpful. – Basil Bourque May 31 '17 at 17:55
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html), and `java.text.SimpleTextFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque May 31 '17 at 17:55