Mohamed Farahat
Mohamed Farahat

Reputation: 761

Convert date to firetstore TimeStamp

i want to convert date as a long seconds to Firestore timestamp

object TimeStampConverter {

fun convertToTimeStamp(months: Int, year: Int): Date? {
    val date = Calendar.getInstance()
    date[Calendar.YEAR] = year // Set the year you want
    date[Calendar.MONTH] = months
    return date.time
}}

i want to convert the date.time that returned from TimeStampConverter function to a Firestore Timestamp.

Upvotes: 2

Views: 965

Answers (2)

kaushalyap
kaushalyap

Reputation: 13677

For future readers come across this

In order to get current timestamp you can easily use now() method from com.google.firebase.Timestamp which is provided by Android Firebase client library

import com.google.firebase.Timestamp

Timestamp.now() // get timestamp for current time

Upvotes: 0

Alex Mamo
Alex Mamo

Reputation: 1

First of all, Firestore timestamps are generated on the server and as Doug Stevenson mentioned in his comment, it can store time units as small as nanoseconds.

However, if you want to convert a year and month to a Firestore Timestamp object, the day, hour, minutes, seconds and nanoseconds components will always be 0. This is happening because those components simply do not exist at all since you are only using the year and month. 0 is just the default value that it is used in this case.

I as android want to update this firebase timestamp field so which data type should we use

As mentioned in the official documentation regarding Firestore data types, the most appropriate way of saving the time and date is as Date, as explained in my answer from the following post:

Now if you want to convert a Timestamp object to a Date object, it means that you are narrowing the conversion (you lose the nanoseconds precision) while converting a Date object to a Timestamp object it means that you are widening the conversion. In this case, as also mentioned before, new precision is added and missing data is filled with zeros.

Upvotes: 3

Related Questions