简体   繁体   中英

How to convert MongoDB ISODate to be compatible with input[type=“date”]

I'm having an issue where I'm using mongoDB to store dates as part of objects, and I'm exposing those objects on the front end using Meteor and Angular. What it is giving me is almost right, but since I'm trying to keep the data-binding working, I can't work out how to manipulate the objects before giving them to Meteor.

I believe what I need to do is modify each object which matches the db.table.find() query before returning it to Meteor.

The objects in the table have this structure:

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

I am publishing them like this:

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

The front end is hooked up like this.

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

The problem with this is the format of the date: it includes everything from the "T", when it shouldn't have that part for input date fields. How do I modify the object on the way out of the database?

You need to format the date using a library like 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:

I haven't used Angular before so I'm not sure how to implement it with the angular logic, however if you write some sort of a module called formatDate() you can re-use it over and over

import moment from 'moment';

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

export default formatDate;

Then you can use that function anywhere you deal with dates in your application:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM