【问题标题】:How to convert MongoDB ISODate to be compatible with input[type="date"]如何将 MongoDB ISODate 转换为与 input[type="date"] 兼容
【发布时间】:2017-05-06 03:15:17
【问题描述】:

我遇到了一个问题,我使用 mongoDB 将日期存储为对象的一部分,并且我正在使用 Meteor 和 Angular 在前端公开这些对象。它给我的几乎是正确的,但由于我试图保持数据绑定正常工作,我无法弄清楚如何在将对象交给 Meteor 之前对其进行操作。

我相信我需要做的是修改与 db.table.find() 查询匹配的每个对象,然后再将其返回给 Meteor。

表中的对象具有这样的结构:

{
    date: ISODate(2017-05-04T14:00:00Z),
    note: "Foo"
}

我是这样发布它们的:

Meteor.publish('tasks', function tasksPublication() {
    var tasks = Tasks.find();
    return tasks;
});

前端是这样挂起来的。

<label>Date: <input type="date" ng-value="{{task.date}}" /> </label>

问题在于日期的格式:它包括“T”中的所有内容,而输入日期字段不应该包含该部分。 出库时如何修改对象?

【问题讨论】:

    标签: mongodb meteor angular-meteor


    【解决方案1】:

    您需要使用像moment.js 这样的库来格式化日期

    meteor npm install moment --save

    import moment from 'moment';
    
    const date = ISODate(2017-05-04T14:00:00Z);
    
    const formattedDate = moment(date).format('DD-MM-YYYY'); //04-05-2017
    

    You can read all about formatting using moment here:

    我之前没有使用过 Angular,所以我不确定如何使用 Angular 逻辑来实现它,但是如果你编写了某种名为 formatDate() 的模块,你可以一遍又一遍地重复使用它

    import moment from 'moment';
    
    const formatDate = (date) => {
        return moment(date).format('DD-MM-YYYY'); //change the format string to your preference
    }
    
    export default formatDate;
    

    然后,您可以在应用程序中处理日期的任何地方使用该函数:

    import formatDate from '/path/to/formatdate';
    

    【讨论】:

    • 感谢您的回复。我对 Meteor 或 Angular 也不是很熟悉,所以理解数据如何流动有点令人困惑,但我会看看我是否可以做到这一点。
    猜你喜欢
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    • 2022-10-17
    • 1970-01-01
    • 2017-04-01
    相关资源
    最近更新 更多