截至日期和时间的Firebase时间戳

6ss1mwsb  于 2022-09-18  发布在  Java
关注(0)|答案(22)|浏览(202)

我正在为我的聊天应用程序使用Firebase。在Chat对象中,我使用Firebase.ServerValue.TIMESTAMP方法添加时间戳。

我需要使用此时间戳在我的聊天应用程序中显示消息接收时间。

如果是当前时间,我只需要显示时间。如果有天差,我需要显示日期和时间,或者只显示日期。

我使用了以下代码来转换Firebase时间戳,但我没有获得实际时间。

var timestamp = '1452488445471';
var myDate = new Date(timestamp*1000);
var formatedTime=myDate.toJSON();

请为这个问题提出解决方案

e0bqpujr

e0bqpujr1#

试试这个,

var timestamp = firebase.firestore.FieldValue.serverTimestamp()
var timestamp2 = new Date(timestamp.toDate()).toUTCString()
ou6hu8tu

ou6hu8tu2#

Firebase.ServerValue.TIMESTAMP is the same as new Date().getTime().

Convert it:

var timestamp = '1452488445471';
var myDate = new Date(timestamp).getTime();
gfttwv5a

gfttwv5a3#

This code is work for me

<script src="https://www.gstatic.com/firebasejs/4.5.1/firebase.js"></script>
<script>
var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
};

firebase.initializeApp(config);
var reff = firebase.database().ref('message');
reff.on('value',haveData, haveerr);
function haveData(datahave){
    var existval= datahave.val();
    var chabi=Object.keys(existval);
    for(var d2=0;d2< chabi.length;d2++){
        var r=chabi[d2];
        var exitval=existval[r].Message;
        var exitval1=existval[r].Name;
        var exit=existval[r].Email;
        var exitval2=existval[r].Subject;
        var timestamp=existval[r].timestamp;
        var sdate=new Date(timestamp);
        var Year=sdate.getFullYear();
        var month=sdate.getMonth()+1;
        var day=sdate.getDate();
        var hh=sdate.getHours();
        var mm=sdate.getMinutes();
        var ss=sdate.getSeconds();
    }
}

function haveerr(e){
     console.log(e);
}
</script>
gojuced7

gojuced74#

First Of All Firebase.ServerValue.TIMESTAMP is not working anymore for me.

So for adding timestamp you have to use Firebase.database.ServerValue.TIMESTAMP

And the timestamp is in long millisecond format.To convert millisecond to simple dateformat .

Ex- dd/MM/yy HH:mm:ss

You can use the following code in java:

To get the timestamp value in string from the firebase database

String x = dataSnapshot.getValue (String.class);

The data is in string now. You can convert the string to long

long milliSeconds= Long.parseLong(x);

Then create SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm:ss");

Now convert your millisecond timestamp to ur sdf format

String dateAsString = sdf.format (milliSeconds);

After that you can parse it to ur Date variable

date = sdf.parse (dateAsString);
d6kp6zgx

d6kp6zgx5#

let jsDate = new Date(date.seconds * 1000 + date.nanoseconds / 1000000);
wdebmtf2

wdebmtf26#

I converted to this format

let timestamp = '1452488445471';
let newDate = new Date(timestamp * 1000)
let Hours = newDate.getHours()
let Minutes = newDate.getMinutes()
const HourComplete = Hours + ':' + Minutes
let formatedTime = HourComplete
console.log(formatedTime)
06odsfpq

06odsfpq7#

对我来说,当时间戳是整数而不是字符串时,它是有效的:

var timestamp = '1452488445471';
var myDate = new Date(parseInt(timestamp));
myDate.toDateString()
iibxawm4

iibxawm48#

遍历这段代码就是为我工作的准确代码。

querySnapshot.docs.forEach((e) => {
   var readableDate = e.data().date.toDate();
   console.log(readableDate);
}
dddzy1tm

dddzy1tm9#

var date = new Date((1578316263249));//data[k].timestamp
console.log(date);
6yt4nkrj

6yt4nkrj10#

import firebaseAPP from 'firebase/app';

    public Date2firestoreTime(fromDate: Date) {
       return firebaseAPP.firestore.Timestamp.fromDate(fromDate).toMillis()
    }
    public firestoreTime2Date(millisecDate: number) {
       return firebaseAPP.firestore.Timestamp.fromMillis(millisecDate).toDate()
    }

    //usage:
    let FSdatenow = this.Date2firestoreTime(new Date())
    console.log('now to firestore TimeStamp', FSdatenow)
    let JSdatenow = this.firestoreTime2Date(FSdatenow)
    console.log('firestore TimeStamp to Date Obj', JSdatenow)
xwbd5t1u

xwbd5t1u11#

new Date(timestamp.toDate()).toUTCString()

ao218c7q

ao218c7q12#

Timestamp是一个对象:

timestamp = {
  nanoseconds: 0,
  seconds: 1562524200
}

console.log(new Date(timestamp.seconds*1000))
c3frrgcw

c3frrgcw13#

这很简单。使用该函数获取服务器时间戳,单位为毫秒仅一次

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 );
    });
};

现在你可以在任何地方使用它,就像这样:

getServerTime( function( now ) {
    console.log( now );
});

为什么使用这种方式?

根据最新的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;
});

虽然Firebase.datase.ServerValue.TIMESTAMP要准确得多,而且对于大多数读/写操作来说也更可取,但有时估计客户端相对于Firebase实时数据库服务器的时钟偏差可能很有用。您可以将回调附加到位置/.info/serverTimeOffset,以获取Firebase实时数据库客户端添加到本地报告时间(以毫秒为单位的纪元时间)以估计服务器时间的值(以毫秒为单位)。请注意,此偏移量的准确性可能会受到网络延迟的影响,因此主要用于发现时钟时间中的较大(>1秒)差异。

https://firebase.google.com/docs/database/web/offline-capabilities

wwodge7n

wwodge7n14#

使用Firebase Firestone 18.0.1(com.google.Firebase.Timestamp)

val timestamp = (document.data["timestamp"] as Timestamp).toDate()
pw136qt2

pw136qt215#

下面是一个将值从Firebase Timestamp类型转换为JS Date的安全方法,如果该值不是Timestamp,则该方法会按原样返回该值

适用于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;
}

相关问题