Skip to content

Instantly share code, notes, and snippets.

@brianjychan
Last active March 29, 2020 04:46
Show Gist options
  • Save brianjychan/f468145be98eaf3fe44f77484bc7a0ef to your computer and use it in GitHub Desktop.
Save brianjychan/f468145be98eaf3fe44f77484bc7a0ef to your computer and use it in GitHub Desktop.
Convert Firestore Timestamps to text format using javascript-time-ago. Works when Timestamps are retrieved both from client SDK or Cloud Functions. JS/ Typescript
import app from 'firebase/app'
import 'firebase/firestore'
import TimeAgo from 'javascript-time-ago'
// Load locale-specific relative date/time formatting rules.
import en from 'javascript-time-ago/locale/en'
// Add locale-specific relative date/time formatting rules.
TimeAgo.addLocale(en)
// Adapted from Andrey Gordeev's answer at:
// https://stackoverflow.com/questions/56245156/timestamp-from-firestore-gets-converted-to-a-map-when-using-cloud-function
class MyClass {
timeAgo: TimeAgo
constructor() {
this.timeAgo = new TimeAgo('en-US')
}
getTimeText = (timeObject: any) => {
// Convert to time text once it's of type firestore.Timestamp
const getTextFromTimestamp = (timestamp: app.firestore.Timestamp) => {
return this.timeAgo.format(timestamp.toDate())
}
if (timeObject instanceof app.firestore.Timestamp) {
// Check if Timestamp (accessed from client SDK)
return getTextFromTimestamp(timeObject)
} else if (Object.prototype.toString.call(timeObject) === '[object Object]') {
// Check if it's a Map (accessed from Cloud Functions)
const seconds = timeObject['_seconds']
const nanoseconds = timeObject['_nanoseconds']
if (seconds && nanoseconds) {
const timestamp = new app.firestore.Timestamp(seconds, nanoseconds)
return getTextFromTimestamp(timestamp)
}
}
console.log('Couldn\'t parse time', timeObject)
// Fallback
return 'some time ago'
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment