2

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.

Mohamed Farahat
  • 751
  • 1
  • 7
  • 12
  • If all you have is a year and month, that's not very well suited for a Timestamp, which represents a very specific moment in time to nanosecond precision. – Doug Stevenson Dec 30 '19 at 17:51
  • ok , let me put you in the situation , we used goLang to set a list of products and each element has a timestamp field , i as android want to update this firebase timestamp field so which data type should we use ! and what are other constrains that we need to turn date to firebase timestamp ! – Mohamed Farahat Dec 30 '19 at 22:06

2 Answers2

3

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.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
0

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
user158
  • 12,852
  • 7
  • 62
  • 94