String a Date formatted correctly


I have a question, as far as dates are concerned in Java. I receive several dates in String format but each of them comes in a different format, so they do not come in a certain format.

Dates with formats such as:

  • 21/05 / 2018Z09: 14: 32.123
  • 05/21/2018
  • 05-21-2018 / 09: 14: 32
  • 05-21-2018 09:14:32

And so many more dates ...

The goal is to pass these dates to a specific format. which would be the following: 2018-05-21 09:14:32 - > (yyyy-MM-dd HH: mm: ss).

I do not know if I do not understand the SimpleDateFormat correctly, but I can not return the date in the format I want.

    Date fecha = new Date("2018-01-23T09:56:04+01:00");
            DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
            String strDate = sdf.format(fecha);
            Date dates = new Date();  
            try {

                dates = dateFormat.parse(strDate);
            } catch (ParseException ex) {
asked by Javivo 21.05.2018 в 11:06

1 answer


In summary, you receive several dates in different formats in String, and what you want is to change the format of the date you receive. If so, follow the steps below:

The first thing we are going to do is create our variables:

SimpleDateFormat conver = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date fecha;
private String nuevoFormato;

The variable conver will be to perform the conversion to the format you want, the variable fecha , will serve to store the conversion from String to Date, and later the variable nuevoFormato , will be the conversion from Date to String again to get the format you want.

First let's convert the dates strings you receive to Date:

try {
    fecha = conver.parse(fechaQueRecibes);
} catch (ParseException e) {

We are going to place everything inside an exception, in case it generates an error. First we place the variable fecha of the type Date, to store the date of the type String that you receive in any format. And we use SimpleDateFormat with your parse method to convert from String to Date. Once obtained this, we proceed to convert the Date date into String again (if you do not need to convert the date to String, you can leave it in this step and keep a Date date but with the format you want) .

To convert from Date to String, we use the following:

try {
        nuevaFormato = conver.format(fecha.getTime());
} catch (Exception ex) {

Finally, you use the variable nuevoFormato , to store the conversion from Date to String and you're done.

answered by 06.06.2018 в 01:04