Javascript Firebase TIMESTAMP 到日期和时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34718668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Firebase TIMESTAMP to date and Time
提问by Kichu
I am using firebase for my chat application. In chat object I am adding time stamp using Firebase.ServerValue.TIMESTAMP
method.
我正在将 firebase 用于我的聊天应用程序。在聊天对象中,我使用Firebase.ServerValue.TIMESTAMP
方法添加时间戳。
I need to show the message received time in my chat application using this Time stamp .
我需要使用此时间戳在我的聊天应用程序中显示消息接收时间。
if it's current time i need to show the time only.It's have days difference i need to show the date and time or only date.
如果是当前时间,我只需要显示时间。它有天差,我需要显示日期和时间或只显示日期。
I used the following code for convert the Firebase time stamp but i not getting the actual time.
我使用以下代码转换 Firebase 时间戳,但没有得到实际时间。
var timestamp = '1452488445471';
var myDate = new Date(timestamp*1000);
var formatedTime=myDate.toJSON();
Please suggest the solution for this issue
请提出此问题的解决方案
回答by Bek
Firebase.ServerValue.TIMESTAMPis not actual timestamp it is constant that will be replaced with actual value in server if you have it set into some variable.
Firebase.ServerValue.TIMESTAMP不是实际时间戳,它是常量,如果您将其设置为某个变量,它将被服务器中的实际值替换。
mySessionRef.update({ startedAt: Firebase.ServerValue.TIMESTAMP });
mySessionRef.on('value', function(snapshot){ console.log(snapshot.val()) })
//{startedAt: 1452508763895}
if you want to get server time then you can use following code
如果你想获得服务器时间,那么你可以使用以下代码
fb.ref("/.info/serverTimeOffset").on('value', function(offset) {
var offsetVal = offset.val() || 0;
var serverTime = Date.now() + offsetVal;
});
回答by Tiago Gouvêa
In fact, it only work to me when used
事实上,它只在使用时对我有用
firebase.database.ServerValue.TIMESTAMP
With one 'database' more on namespace.
在命名空间上多了一个“数据库”。
回答by Kyle Finley
For those looking for the Firebase Firestoreequivalent. It's
对于那些正在寻找 Firebase Firestore等效项的人。它是
firebase.firestore.FieldValue.serverTimestamp()
e.g.
例如
firebase.firestore().collection("cities").add({
createdAt: firebase.firestore.FieldValue.serverTimestamp(),
name: "Tokyo",
country: "Japan"
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
回答by Dan Alboteanu
inside Firebase Functions transform the timestamp like so:
Firebase 函数内部转换时间戳,如下所示:
timestampObj.toDate()
timestampObj.toMillis().toString()
documentation here https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp
此处的文档https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp
回答by Matt
Solution for newer versions of Firebase (after Jan 2016)
较新版本 Firebase 的解决方案(2016 年 1 月之后)
The proper way to attach a timestamp to a database update is to attach a placeholder value in your request. In the example below Firebase will replace the createdAt
property with a timestamp:
将时间戳附加到数据库更新的正确方法是在您的请求中附加一个占位符值。在下面的示例中,Firebase 将createdAt
使用时间戳替换该属性:
firebaseRef = firebase.database().ref();
firebaseRef.set({
foo: "bar",
createdAt: firebase.database.ServerValue.TIMESTAMP
});
According to the documentation, the value firebase.database.ServerValue.TIMESTAMP
is: "A placeholder value for auto-populating the current timestamp (time since the Unix epoch, in milliseconds) by the Firebase Database servers."
根据文档,该值为firebase.database.ServerValue.TIMESTAMP
:“Firebase 数据库服务器自动填充当前时间戳(自 Unix 纪元以来的时间,以毫秒为单位)的占位符值。”
回答by zemunkh
For Firestore that is the new generation of database from Google, following code will simply help you through this problem.
对于 Google 的新一代数据库 Firestore,以下代码将简单地帮助您解决此问题。
var admin = require("firebase-admin");
var serviceAccount = require("../admin-sdk.json"); // auto-generated file from Google firebase.
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
var db = admin.firestore();
console.log(admin.firestore.Timestamp.now().toDate());
回答by vineet
timestamp is an object
时间戳是一个对象
timestamp= {nanoseconds: 0,
seconds: 1562524200}
console.log(new Date(timestamp.seconds*1000))
回答by beytarovski
It is simple. Use that function to get server timestamp as milliseconds one time only:
很简单。使用该函数仅一次以毫秒为单位获取服务器时间戳:
var getServerTime = function( cb ) {
this.db.ref( '.info/serverTimeOffset' ).once( 'value', function( snap ) {
var offset = snap.val();
// Get server time by milliseconds
cb( new Date().getTime() + offset );
});
};
Now you can use it anywhere like that:
现在你可以在任何地方使用它:
getServerTime( function( now ) {
console.log( now );
});
Why use this way?
为什么要用这种方式?
According to latest Firebase documentation, you should convert your Firebase timestamp into milliseconds. So you can use estimatedServerTimeMs
variable below:
根据最新的 Firebase 文档,您应该将 Firebase 时间戳转换为毫秒。所以你可以使用estimatedServerTimeMs
下面的变量:
var offsetRef = firebase.database().ref(".info/serverTimeOffset");
offsetRef.on("value", function(snap) {
var offset = snap.val();
var estimatedServerTimeMs = new Date().getTime() + offset;
});
While firebase.database.ServerValue.TIMESTAMP is much more accurate, and preferable for most read/write operations, it can occasionally be useful to estimate the client's clock skew with respect to the Firebase Realtime Database's servers. You can attach a callback to the location /.info/serverTimeOffset to obtain the value, in milliseconds, that Firebase Realtime Database clients add to the local reported time (epoch time in milliseconds) to estimate the server time. Note that this offset's accuracy can be affected by networking latency, and so is useful primarily for discovering large (> 1 second) discrepancies in clock time.
虽然 firebase.database.ServerValue.TIMESTAMP 更准确,并且更适合大多数读/写操作,但有时估计客户端相对于 Firebase 实时数据库服务器的时钟偏差会很有用。您可以将回调附加到位置 /.info/serverTimeOffset 以获取 Firebase 实时数据库客户端添加到本地报告时间(以毫秒为单位的纪元时间)以估计服务器时间的值(以毫秒为单位)。请注意,此偏移量的准确性可能会受到网络延迟的影响,因此主要用于发现时钟时间中的大(> 1 秒)差异。
https://firebase.google.com/docs/database/web/offline-capabilities
https://firebase.google.com/docs/database/web/offline-capabilities
回答by rockdaswift
Working with Firebase Firestone 18.0.1 (com.google.firebase.Timestamp)
使用 Firebase Firestone 18.0.1 (com.google.firebase.Timestamp)
val timestamp = (document.data["timestamp"] as Timestamp).toDate()
回答by Serge Seletskyy
Here is a safe method to convert a value from firebase Timestamp type to JS Date in case the value is not Timestamp the method returns it as it is
这是一种将值从 firebase Timestamp 类型转换为 JS Date 的安全方法,以防该值不是 Timestamp 该方法按原样返回它
Works for Angular 7/8/9
适用于 Angular 7/8/9
import firebase from 'firebase';
import Timestamp = firebase.firestore.Timestamp;
export function convertTimestampToDate(timestamp: Timestamp | any): Date | any {
return timestamp instanceof Timestamp
? new Timestamp(timestamp.seconds, timestamp.nanoseconds).toDate()
: timestamp;
}