Save a date value in the firestore

Asked

Viewed 137 times

1

I’m trying to save a data value in the firestore, but I’m having a conversion problem when I take the value of a EditText and send it to become a date type value. The attempt I made was this one.

private String dateToTimestampString(String dateString){

    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    Date parsedDate;
    Timestamp timestamp;

    try {
        parsedDate = dateFormat.parse(dateString);
        timestamp = new Timestamp(parsedDate);
        return timestamp.toString();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return "";
}

Man EditText

String dt = editDiasTrabalhado.getText().toString();

long dtL = Long.parseLong(dateToTimestampString(dt));

rel.setEditDiasTrabalhado(dtL);

The error being generated is this:

java.lang.Numberformatexception: For input string: "Timestamp(Seconds=1563764400, nanoseconds=0)"

On the field editDiasTrabalhado I am setting the current date as follows: dd/MM/yyyy.

1 answer

1

Your method dateToTimestampString returns:

return timestamp.toString();

And the method toString() class Timestamp returns a String containing the text that appears in the exception: "Timestamp(seconds=1563764400, nanoseconds=0)".

Only that the method Long.parseLong expects to receive a String containing only numbers (with the exception of the first character, which may be a sign of + or -). Accordingly, the String that you are passing does not match the format that the method expects, and so the error.

But perhaps this is not the solution. It was not very clear what should be passed to setEditDiasTrabalhado. Is it the number of days? If it is, it makes no sense to have a date, since a date represents a specific day, and is different from a number of days.

But if you’re trying to get the numerical value of timestamp, so you don’t even have to create the Timestamp. Just use the java.util.Date (that you are already getting through the Parsing) and extract this value from it:

private Date parseDate(String dateString) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    try {
        return dateFormat.parse(dateString);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return null;
}

...
Date date = parseDate(dateString);
if (date == null) {
    ... mostrar mensagem de erro, etc
} else {
    // obter o valor do timestamp
    long dtL = date.getTime();
    ...
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.