Alexandru Stroescu
Alexandru Stroescu

Reputation: 1167

Timestamp saves a map instead of the actual timestamp

When I save the date Timestamp, that I get using Timestamp.now(), it saves me this weird map instead of the actual time. I should get only the timestamp located in data/time, not that whole map. What's weid is the fact that I actually save to Firestore a Timestamp called date, not a map. Here's the picture:

That's the function I wrote to save a twice to firestore (twice is an invented name, it actually means note)


    private void saveTwice() {
        String title = mTitle.getText().toString();
        String description = mDescription.getText().toString();
        Timestamp date = Timestamp.now();

        Log.d(TAG, "saveTwice: " + date.toString());

        if (title.trim().isEmpty() || description.trim().isEmpty()) {
            Toast.makeText(this, "Please insert a title and description", Toast.LENGTH_SHORT).show();
            return;
        }

        CollectionReference twiceRef = FirebaseFirestore.getInstance()
                .collection("Twices");
        twiceRef.add(new Twice(title, description, date));
        Toast.makeText(this, "Twice added", Toast.LENGTH_SHORT).show();
        Intent back = new Intent(AddTwice.this, MainActivity.class);
        startActivity(back);
    }
}

And there's Twice.java.

package com.example.twicev11;

import android.text.format.DateFormat;

import com.google.firebase.Timestamp;
import com.google.firebase.firestore.FieldValue;

import java.util.Calendar;
import java.util.Locale;


public class Twice {
    private String title, description;
    private Timestamp date;

    public Twice() {
        //empty constructor needed
    }

    public Twice(String title, String description, Timestamp date) {
        this.title = title;
        this.description = description;
        this.date = date;
    }

    public String getTitle() {
        return title;
    }

    public String getDescription() {
        return description;
    }

    public Calendar getDate() {
        Calendar cal = Calendar.getInstance(Locale.getDefault());
        cal.setTimeInMillis(date.toDate().getTime());

        return cal;
    }


}

I expect to get this, instead of that ugly map

Upvotes: 0

Views: 746

Answers (2)

Doug Stevenson
Doug Stevenson

Reputation: 317342

If you want to store a Timestamp type field in Cloud Firestore, you will need to provide either a Java Date type object, or a Firestore Timestamp type objects.

If you have a Calendar in hand, you can convert that to a Date with its getTime() method. Or you can construct your own Firestore Timestamp object.

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 598668

You're storing a Calendar object, which contains much more information than just the date. If you want to just store the date, store calendar.getTime()

Upvotes: 2

Related Questions