How do I change date time format in Android?

public class MainActivity extends AppCompatActivity {
    private Date oneWayTripDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String date ="2017-05-05 13:58:50 ";
        SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat output = new SimpleDateFormat("MMMM dd,yyyy @hh:mm:ss aa");
        try {
            oneWayTripDate = input.parse(date);  // parse input
        } catch (ParseException e) {
            e.printStackTrace();
       }
       Log.e("===============","======currentData======"+output.format(oneWayTripDate);
    }
}

Here is working code

public String parseDateToddMMyyyy(String time) {
    String inputPattern = "yyyy-MM-dd HH:mm:ss";
    String outputPattern = "dd-MMM-yyyy h:mm a";
    SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
    SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);

    Date date = null;
    String str = null;

    try {
        date = inputFormat.parse(time);
        str = outputFormat.format(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return str;
}

Documentation: SimpleDateFormat | Android Developers


Use this code like below:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy hh:mm a");
String date = formatter.format(Date.parse("Your date string"));

Hope it will help you.


    SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy  hh:mm a");
    String date = format.format(Date.parse("Your date string"));

Tags:

Android