【问题标题】:Firestore: Convert time object to timestampFirestore:将时间对象转换为时间戳
【发布时间】:2021-01-18 00:33:46
【问题描述】:

我将 vue.js 用于我的电子商务项目。 我想在firestore集合中设置销售时间限制。

ex)如果用户想在 15:00 停止销售他或她的产品,用户可以输入 15:00。

现在我可以在我的集合中设置时间对象。 但我想将其转换为时间戳。

我怎样才能实现它?

我在模板标签中这样设置this.limit。

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

这是脚本标签。

<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>

【问题讨论】:

  • 目前还不清楚您到底想要实现什么。 this.limit 的值是否设置在某处?你做了const timestamp = firebase.firestore.FieldValue.serverTimestamp(),但你不使用它(即做limit: this.limit.timestamp不会取timestamp的值)。是否要将“now”的值分配给 Firestore 文档中的时间戳字段 limit
  • 抱歉,我编辑了我的问题。我的模板标签中有输入字段来设置 this.time。我想设置用户选择的时间。

标签: javascript firebase vue.js google-cloud-firestore timestamp


【解决方案1】:

您没有指明时间戳是否应采用当天的日期。

假设您想在 Firestore 文档中添加今天 15:00 的时间戳。执行以下操作:

  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(() => ...)

请注意,firebase.firestore.FieldValue.serverTimestamp()“返回与set()update() 一起使用的标记,以在写入的数据中包含服务器生成的时间戳”,这将由 Firestore 后端计算,不在前端。

【讨论】:

  • @YoheiUmezu 嗨,您有时间看一下建议的答案吗?
  • 我刚才试过了,你的回答奏效了!非常感谢。
猜你喜欢
  • 2019-05-10
  • 1970-01-01
  • 2020-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
  • 2017-07-19
  • 1970-01-01
相关资源
最近更新 更多