Formatting dates for display and storage

0

In this Android application, I have a date field in the SQLITE database table, defined as:

    String createTable = "CREATE TABLE " + TABLE_RUNS + " ( " +
            _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COL_RUN_DATE + " DATETIME DEFAULT CURRENT_DATE, " +...

When you insert a new record, it automatically places the date as YYYY-MM-DD.

At the time of viewing, I step the date by this method that returns it in DD / MM / YY format. This is done by calling the following method:

String strDateToShow(String dateToFormat){
    // format date to display
    SimpleDateFormat formatFrom, formatTo;
    formatFrom = new SimpleDateFormat("yyyy-MM-dd");
    formatTo   = new SimpleDateFormat();
    if(dateToFormat != null) {
        try {
            Date mDate = formatFrom.parse(dateToFormat);
            dateToFormat = formatTo.format(mDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if(dateToFormat == null){
        dateToFormat = formatTo.format(new Date());
    }
    return stringToSpace(dateToFormat);
}

Example: enter 2017-01-26          sai 01/26/17

Later, when updating the registry, I try to do the reverse, but it is not working. Via debug I noticed that there is always exception in the line commented below:

private String strDateToStore(String dateToFormat){
    // format date
    SimpleDateFormat formatFrom, formatTo;
    formatFrom = new SimpleDateFormat();
    formatTo = new SimpleDateFormat("yyyy-MM-dd");
    if(dateToFormat != null) {
        try {
            Date mDate = formatFrom.parse(dateToFormat); // <-- aqui ocorre a exceção.
            dateToFormat = formatTo.format(mDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if(dateToFormat == null){
        dateToFormat = formatTo.format(new Date());
    }
    return stringToSpace(dateToFormat);
}

Example: Enter 26/01/17 and leaves 26/01/17 when it should be leaving 2017-01-26

The display format may vary. If it was always day / month / year, it was just to make it explicit, but the format should be the place where the application is being used.

PS. The solution does not need to use the methods. Just convert from and to what is good.

UPDATE: Due to the content of the answers, it is necessary to clarify the situation a little more.

When the record is generated, the date is automatically entered in the format yyyy-MM-dd, for example, 2017-01-25. The records are shown in a list. At this time, the date is converted to the display format. At some point, the user decides to change the registry data and that will update the database, I take the date and convert the display format, whatever, in the format yyyy-MM-dd, which is the crux of the matter proposal.

Some comments:

1) Database operations methods, use a POJO, so I need to reformat the date. If it were an explicit UPDATE (SQL) statement, I could skip the date and it would be retained, but as it is of type

database.update(TABLE_RUNS, values, whereClause, null);

I have to resume all values.

2) My solution for jerico: I'm going to save the original date in%% of textView of the date and time to update, instead% I'll% use tag . Resolves, but it's a twist. It would be legal (and less asnice) to have one (or two) universal method (s) for conversion from / to dates.

    
asked by anonymous 26.01.2017 / 03:10

3 answers

0

With the help of colleagues and some modifications to the code, I got the desired effect.

This method returns a string formatted as a system date, from a string in the format yyyy-MM-dd. Enter 2017-01-26, exit 26-1-17 or 1-26-17, according to device settings.

public String convertDateToShow(String strDate){
    // formato de entrada deve ser 2017-01-17
    SimpleDateFormat dateFormatIn = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
    // sem argumentos, pega o formato do sistema para exibir a data
    SimpleDateFormat dateFormatOut = new SimpleDateFormat();
    // com argumentos formato e locale a saida e sempre a mesma
    //  SimpleDateFormat dateFormatOut = new SimpleDateFormat("dd-MM-yy", Locale.US);
    Date convertedDate = new Date();
    try {
        convertedDate = dateFormatIn.parse(strDate);
    } catch (ParseException e) {
            e.printStackTrace();
    }


    return stringToSpace(String.valueOf(dateFormatOut.format(convertedDate)));
}

// stringToSpace() retorna a string a esquerda do primeiro espaço da string passada.
// necessario porque a conversao retorna dd/MM/yy 12:00 hs
private String stringToSpace(String string){

    int spaceIndex = string.indexOf(" ");
    if(spaceIndex > 0) {
        string = string.substring(0, spaceIndex);
    }
    return string;
}

Returns a string formatted as a date in the format yyyy-MM-dd, from a string formatted as a system date. Enter 26-1-17 or 1-26-17 and exit 2017-26-01.

public String convertDateToStore(String strDate){
    // formato de entrada do sistema (dd-MM-yy ou MM-dd-yy ou...)
    // sem argumentos, pega o formato do sistema para exibir a data
    SimpleDateFormat dateFormatIn = new SimpleDateFormat();
    // com argumentos formato e locale a saida e sempre a mesma
    // SimpleDateFormat dateFormatIn = new SimpleDateFormat("dd-MM-yy", Locale.US);
    SimpleDateFormat dateFormatOut = new SimpleDateFormat("yyyy-MM-dd", Locale.US);

    Date convertedDate = new Date();
    try {
        convertedDate = dateFormatIn.parse(strDate);
    } catch (ParseException e) {
            e.printStackTrace();
    }
    return String.valueOf(dateFormatOut.format(convertedDate));
}

E zefini.

    
27.01.2017 / 02:35
2

This error happens because you do not put the input format in SimpleDateFormat, try changing the line below

From:

formatFrom = new SimpleDateFormat();

To:

formatFrom = new SimpleDateFormat("dd/MM/yy");

You can also use a single method to reuse the code, instead of using two methods that are practically the same:

private String strToDate(String dateToFormat, String formatIn, String formatOut){
    // format date
    SimpleDateFormat formatFrom, formatTo;
    formatFrom = new SimpleDateFormat(formatIn);
    formatTo = new SimpleDateFormat(formatOut);
    if(dateToFormat != null) {
        try {
            Date mDate = formatFrom.parse(dateToFormat); // <-- aqui ocorre a exceção.
            dateToFormat = formatTo.format(mDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if(dateToFormat == null){
        dateToFormat = formatTo.format(new Date());
    }
    return stringToSpace(dateToFormat);
}

And call the same method but with different parameters.

For reading:

String dataLeitura = strToDate(data, "yyyy-MM-dd", "dd/MM/yy");

And for writing:

String dataEscrita = strToDate(data, "dd/MM/yy", "yyyy-MM-dd");

    
26.01.2017 / 11:28
1

What you have to note is that you are entering a format different from what you are using in SimpleDateFormat() . Basically you have to use two formats, one input and one output. For input in this case would be 26/01/17 and output 2017-01-26 , then the parameter of method SimplesDateFormat() respectively would be dd-MM-yy input and yyyy-MM-dd output. See the method below how the problem can be solved:

public String convertStringInDate(String str){
    // formato de entrada deve ser 26/01/17 
    SimpleDateFormat dateFormatIn = new SimpleDateFormat("dd-MM-yy", Locale.US);
    SimpleDateFormat dateFormatInOut = new SimpleDateFormat("yyyy-MM-dd", Locale.US);

    Date convertedDate = new Date();
    try {
        convertedDate = dateFormatIn.parse(str);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return String.valueOf(dateFormatInOut.format(convertedDate));
}

For more details, see in the documentation (en) .

EDIT

In order to set the locale to SimpleDateFormat , although sometimes set to getDefault() , care must be taken because it may not be appropriate for all use cases, especially output read devices. See a note in the documentation :

  

The default location is not appropriate for   device. The best option is usually Locale.US - this location   is guaranteed to be available on all devices, and is   frequently used.

See more details here. .

    
26.01.2017 / 11:39