user3397260
user3397260

Reputation: 271

Storing the time and the Data in firebase Database

Im trying to create a JavaScript function that is storing some information in firebase Database each time it is called. One information that I want to store is the current Date and Time that the function has been called. I’ve create something on my own but the formation of the date and time isn’t quite how I want it to be. My source code of the function is the following:

function AddtoDatabase(id,title,description){
    var rootRef = firebase.database().ref().child(`notifications/${id}`);
    var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds              

    rootRef.push({
        title:`${title}`,
        description:`${description}`,
        //time:`${new Date().toISOString().split('T')[0]}`
        time:`${(new Date(Date.now() - tzoffset)).toISOString().slice(0, -1)}`
    });
}

Using the source code above i get the following result from date and time: enter image description here

How can I edit the code to get just

Received at:2018-03-14 09:48

Can anyone please help me?

Upvotes: 0

Views: 400

Answers (2)

Utkarsh Bhatt
Utkarsh Bhatt

Reputation: 1606

I think that you can achieve this simply using the Date() object's native methods like getFullYear(), getFullMonth() etc.

Here's the code.

const date = new Date();
const year = date.getFullYear();
const month = date.getFullMonth() + 1 // months start from 0
const day = date.getDay()
const hour = date.getHours();
const minutes = date.getMinutes();

const time = `Received at ${year}-${month}-${day} ${hour}:${minutes}`;

Upvotes: 1

Renaud Tarnec
Renaud Tarnec

Reputation: 83068

You should use the moment library for the formatting: https://momentjs.com/

In particular, look at this part of the documentation: https://momentjs.com/docs/#/displaying/

So in your case you would do:

moment().format("YYYY-MM-DD hh:mm");  

Also, a best practice is to store in your database the number of milliseconds since 1970/01/01, which you can obtain through the JavaScript getTime() method

Upvotes: 0

Related Questions