Last active
March 29, 2020 04:46
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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