Kundan
Kundan

Reputation: 1962

How to customize `serverTimestamp()`?

I want to customise setTimestamp().

firebase.firestore.FieldValue.serverTimestamp()

Currently the output is like August 27, 2019 at 3:38:55 PM UTC+5:30. What to do if I want the result to be August 27, 2019 only ?

Upvotes: 0

Views: 305

Answers (3)

Miki
Miki

Reputation: 1828

In your template you can call .toDate() method of your timestamp field. Do something like:

{{response.data().updatedAt.toDate() | date}}

The date pipe supports multiple formats:

{{response.data().updatedAt.toDate() | date:'short'}}
{{response.data().updatedAt.toDate() | date:'long'}}
... 

See datePipe documentation.

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317948

When a timestamp type field is written to Cloud Firestore, it is just storing a value that describes a moment in time that's the same for all people on earth. What you're seeing in the console is just format that the console is using to make that readable by people. The timezone is represented in your computer's configured timezone.

If you're reading that timestamp in your code and want to format it for display in your app, you'll need to use some date formatting library to make that easy. It looks like you might be using JavaScript, so consider using a library such as momentjs to help with that. You will likely have to convert the timestamp to a Date type object first.

Upvotes: 2

chrismclarke
chrismclarke

Reputation: 2105

Firebase will always set a timestamp in a consistent way.

A Timestamp represents a point in time independent of any time zone or calendar, represented as seconds and fractions of seconds at nanosecond resolution in UTC Epoch time.

As the output you have given has a timezone, I'm guessing this has been applied elsewhere in your code when generating a Date object.

With this date object it is easy enough to reformat to match your desired display. An easy way if you are using angular is to use the date pipe

{{ dateObj | date }}               // output is 'Jun 15, 2015'
{{ dateObj | date:'medium' }}      // output is 'Jun 15, 2015, 9:43:11 PM'
{{ dateObj | date:'shortTime' }}   // output is '9:43 PM'
{{ dateObj | date:'mm:ss' }}       // output is '43:11'

Upvotes: 1

Related Questions