Convert date to timestamp for storing into firebas

2019-07-04 03:00发布

I'm currently using Math.floor(Date.now() / 1000) to get the correct timestamp format to add into a document in Firebase, however, the timestamp gets inserted as a number, and not as a timestamp.

number

I would like to have it inserted as shown below (as a timestamp, not as a number).

enter image description here

Is this possible?

5条回答
太酷不给撩
2楼-- · 2019-07-04 03:36

You can simply use the following line:

var myFirebaseFirestoreTimestampFromDate = firebase.firestore.Timestamp.fromDate(new Date());

.fromDate is a static method from the static Timestamp class from Firebase.

Ref: Firebase Timestamp Doc

查看更多
老娘就宠你
3楼-- · 2019-07-04 03:48

As i can see you are doing date added you would be better using the Server Timestamp and using the below security rule to enforce it.

Security Rules

allow create: if request.resource.data.date_added == request.time && 
              // other rules for the message body

Client side JS code

const message = {
    date_added: firebase.firestore.FieldValue.serverTimestamp();
}
查看更多
虎瘦雄心在
4楼-- · 2019-07-04 03:53

Use

 let lang = 'en-US' // you may use user's computer language: navigator.language || navigator.userLanguage
 let d = new Date(date);
 let options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour:"numeric", timeZone:'short' };
 firebase.database().ref('/thePathYouLikeToSave/date_added').set(d.toLocaleDateString(lang, options));

for more options of the date here the full details

查看更多
疯言疯语
5楼-- · 2019-07-04 03:55

If you want to store a field as a timestamp in Firestore, you'll have to send a JavaScript Date object or a Firestore Timestamp object as the value of the field.

If you want to use Date, simply say new Date(x) where x is the value in milliseconds that you were trying to add before.

If you want to use Timestamp, you would have to do more work to get that x converted into a combination of seconds and nanoseconds to pass to the constructor, as the documentation suggests.

查看更多
男人必须洒脱
6楼-- · 2019-07-04 03:56

To store a date / timestamp in Firestore, you need to send a Date object.

For example, with an existing date, set a field to: new Date("December 10, 1815")

Further information is available in the docs.

查看更多
登录 后发表回答