首页 > 解决方案 > Ionic Firebase Cloudfunctions 时间戳

问题描述

感谢帮助。(更新问题以进行澄清)

1.- 在 ioinic(角度)HTML 中,我要求输入:“开始”。html 表单类型是时间戳,所以在 html 中我可以“以图形方式”选择一个日期。

表格是这样的:

<ion-label>Start</ion-label>
  <ion-datetime formControlName="start" type="timestamp" 
    displayFormat="DMMMYYYY" min="2019" max="2070"></ion-datetime>
</ion-item>

2.-然后我将它作为新日期存储在firestore中(输入值)

example--- {start: new Date(start)} 

在 Firestore 中保存为时间戳:7 月 15 日 01:23:00 UTC 5

作为记录,如果我保存为

{start: start}

它在 Firestore 中保存为:2020-07-15T01:23:00-05:00

,但是我仍然无法在 html 中显示回来......答案可以在这里吗?

3.- 然后,如果我通过 html 获取数据并订阅: 示例:(使用第一个显示的格式)

let d of (data| async).....{{d.start.toDate()|date: "dd/MMM/yy"}}

在 html 中显示我想要的日期...15/jul/2020

4.- 如果我只是将相同的 d.start 传递给另一个函数并直接保存到 Firestore,它仍然会像保存在另一个文档中一样保存。

5.-问题是我将此数据作为数据的一部分传递给可调用的云函数,然后,已经在我检索的 CF 函数中:

const start = data.start;

6.- 这是问题所在,无论我如何尝试,它都不会像在其他 Firestore 文档中那样存储到另一个 Firebase 文档中。

试过:

const start = new Date(data.start)
const start = new Date(data.start.nanoseconds)
const start = new Date(data.starts seconds)
const start = data.start
const start = data.start.nanoseconds.
etc... many combinations truly, read, searched, googled and can't get it.

有时它存储 NaN,有时只是几秒/纳秒,有时返回 500 无效日期格式,有时按我的意愿存储,但使用 1970 年的日期(这是最接近的日期)

我正在尝试仅在 Firestore Cloud Function 中进行转换。

谢谢您的帮助。

标签: angularionic-frameworkgoogle-cloud-firestoregoogle-cloud-functions

解决方案


Ionic 使用 ISO 时间,因此当您以所需格式将数据保存在 firebase 中时,因此当您在表单中重新填写数据时,日期设置为您的格式而不是 iso 格式,因此您需要在 ts 文件中设置值就像声明一样

startDate:Date; 

然后在数据到达使用

this.startDate = newDate(here put the value from firebase).toISOString(); 

与结束日期相同,因此应该可以工作,或者您可以使用管道和地图来实现这一点。

更新部分

您可以在数据库 yyyy-MM-ddT00:00:00.000z 中以 iso 格式正常保存时间,因此当从 firebase 获取数据时正如我在风扇之前告诉您的那样,可以使用管道和映射来解决它,或者通过这种方式:

const splitedDate = firebaseDate.split('T');
const ymd = splitedDate[0];
// now ymd is yyyy-MM-dd
const time = splitedDate[1].split('.');
// now time is 00:00:00
const customDate = this.formatToDate(ymd.split('-'), time);

formatToDate(dtime, time) {
    const date = new Date(dtime[0], (parseInt(dtime[1]) - 1), dtime[2]); 
    const month = date.toLocaleString('default', { month: 'short' }); 
    return `${dtime[2]} of ${month} at ${time}`;
}

推荐阅读