[java] Convert string to date then format the date

I am formatting a string to a date using the code

String start_dt = '2011-01-01';

DateFormat formatter = new SimpleDateFormat("YYYY-MM-DD"); 
Date date = (Date)formatter.parse(start_dt);

But how do I convert the date from YYYY-MM-DD format to MM-DD-YYYY format?

This question is related to java date format simpledateformat

The answer is


Currently, i prefer using this methods:

String data = "Date from Register: ";
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
// Verify that OS.Version is > API 26 (OREO)
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); 
// Origin format
            LocalDate localDate = LocalDate.parse(capitalModels.get(position).getDataServer(), formatter); // Parse String (from server) to LocalDate
            DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("dd/MM/yyyy"); 
//Output format
            data = "Data de Registro: "+formatter1.format(localDate); // Output
            Toast.makeText(holder.itemView.getContext(), data, Toast.LENGTH_LONG).show();
        }else{ 
//Same resolutions, just use legacy methods to oldest android OS versions.
                SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd",Locale.getDefault());
            try {
                Date date = format.parse(capitalModels.get(position).getDataServer());
                SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
                data = "Date from Register: "+formatter.format(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

String start_dt = "2011-01-31";

DateFormat parser = new SimpleDateFormat("yyyy-MM-dd"); 
Date date = (Date) parser.parse(start_dt);

DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy"); 
System.out.println(formatter.format(date));

Prints: 01-31-2011


tl;dr

LocalDate.parse( "2011-01-01" )
         .format( DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) ) 

java.time

The other Answers are now outdated. The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes.

ISO 8601

The input string 2011-01-01 happens to comply with the ISO 8601 standard formats for date-time text. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate ld = LocalDate.parse( "2011-01-01" ) ;

Generate a String in the same format by calling toString.

String output = ld.toString() ;

2011-01-01

DateTimeFormatter

To parse/generate other formats, use a DateTimeFormatter.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) ;
String output = ld.format( f ) ;

01-01-2011


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


enter image description here

String myFormat= "yyyy-MM-dd";
String finalString = "";
try {
DateFormat formatter = new SimpleDateFormat("yyyy MMM dd");
Date date = (Date) formatter .parse("2015 Oct 09");
SimpleDateFormat newFormat = new SimpleDateFormat(myFormat);
finalString= newFormat .format(date );
newDate.setText(finalString);
} catch (Exception e) {

}

In one line:

String date=new SimpleDateFormat("MM-dd-yyyy").format(new SimpleDateFormat("yyyy-MM-dd").parse("2011-01-01"));

Where:

String date=new SimpleDateFormat("FinalFormat").format(new SimpleDateFormat("InitialFormat").parse("StringDate"));

    String start_dt = "2011-01-01"; // Input String

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // Existing Pattern
    Date getStartDt = formatter.parse(start_dt); //Returns Date Format according to existing pattern

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd-yyyy");// New Pattern
    String formattedDate = simpleDateFormat.format(getStartDt); // Format given String to new pattern

    System.out.println(formattedDate); //outputs: 01-01-2011

Tested this code

java.text.DateFormat formatter = new java.text.SimpleDateFormat("MM-dd-yyyy");
java.util.Date newDate = new java.util.Date();
System.out.println(formatter.format(newDate ));

http://download.oracle.com/javase/1,5.0/docs/api/java/text/SimpleDateFormat.html


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to format

Brackets.io: Is there a way to auto indent / format <html> Oracle SQL - DATE greater than statement What does this format means T00:00:00.000Z? How to format date in angularjs How do I change data-type of pandas data frame to string with a defined format? How to pad a string to a fixed length with spaces in Python? How to format current time using a yyyyMMddHHmmss format? java.util.Date format SSSSSS: if not microseconds what are the last 3 digits? Formatting a double to two decimal places How enable auto-format code for Intellij IDEA?

Examples related to simpledateformat

How to convert an Instant to a date format? Get Date Object In UTC format in Java How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss) How to convert date to string and to date again? Java Convert GMT/UTC to Local time doesn't work as expected Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST SimpleDateFormat parse loses timezone java.text.ParseException: Unparseable date Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss SimpleDateFormat returns 24-hour date: how to get 12-hour date?