Skip to content
Advertisement

Firestore: Convert time object to timestamp

I am using vue.js for my e-commerce project. I want to set the sale time limit in the firestore collection.

ex)If user want to stop to sell his or her product at 15:00, user can input 15:00.

Now I could set the time object in my collection. But I want to convert it to timestamp.

How can I achieve it?

I set this.limit like this way in the template tag.

<b-form-input type="time" v-model="limit"></b-form-input>

This is the script tag.

<script>
import fireApp from '@/plugins/firebase'
const firebase = require("firebase");
require("firebase/firestore");
const db = firebase.firestore();
let id = String(id);
import ErrorBar from '@/components/ErrorBar'
import { SpringSpinner } from 'epic-spinners'


  export default {
    name: "Products",
    data() {
      return {
        show: false,
        quantity: "",
        initial: "",
        sale: "",
        limit: ""
      }
    },
    components: {
        SpringSpinner
    },
    created() {

    },
    methods: {
        submitProduct() {
         
                var docRefLimit = db.collection('Profile').doc(user.uid).collection('Product').doc('limit')
                const timestamp = firebase.firestore.FieldValue.serverTimestamp()

                
                docRefLimit.get().then((doc) => {
                    this.show =true;
                    if (doc.exists) {
                        docRefLimit.update({ 
                            limit: this.limit.timestamp,
                        }).then(() => {
                            this.show =false
                        })
                    } else {
                        docRefLimit.set({ 
                            limit: this.limit.timestamp,
                        })
                        .then(() => {
                            this.show =false
                        })
                    }
                }).catch((error) => {
                    console.log("Error getting document:", error);
                });
            },
    }
  }
</script>

Advertisement

Answer

You don’t indicate if the timestamp should take the date of the day.

So let’s imagine you want to add a Timestamp for today at 15:00 to a Firestore document. Do as follows:

  const limitHour = this.limit.substring(0, 2);
  const limitMinutes = this.limit.substring(3, 5);

  let today = new Date();
  today.setHours(limitHour, limitMinutes, 0, 0);

  var docRefLimit = db.collection('Profile').doc(user.uid).collection('Product').doc('limit');
  docRefLimit.update({ limit: today })
   .then(() => ...)

Note that firebase.firestore.FieldValue.serverTimestamp() “returns a sentinel used with set() or update() to include a server-generated timestamp in the written data” which will be calculated by the Firestore backend, not in the frontend.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement