商店&a​​mp;打印日期

时间:2016-02-12 19:03:59

标签: jquery mongodb meteor handlebars.js

我需要使用meteorjs在mongodb中存储日期,例如“myDate”(格式为dd-mm-YYYY),当前日期= myDate时,我想显示它。 (我的项目是一个带注释的列表!)

模板助手:

Template.dates_list.helpers({
  dates: function () {
    return Dates.find({}, { sort: { dateTime: +1 } });
  }
});

模板事件:

Template.newDate_form.events({
  "submit .js-save-newDate-form": function (event) {

    var day, dateTime, note;

    day = event.target.day.value;
    dateTime = event.target.dateTime.value;
    note = event.target.note.value;

    if (Meteor.user()) {
      Dates.insert({
        day: day, 
        dateTime: dateTime, 
        note: note
      });
    } //end of if 
    return true; // start the form submit from reloading the page
  }
});

我的列表模板HTML:

<template name="dates_list">
  <tr>
    <th>{{dateTime}}</th>
    <th>{{day}}</th>
    <th>{{note}}</th>
  </tr>
</template>

我的表格要插入日期

<template name="newDate_form">
  {{#if currentUser}}
    <h4>Push '<b>+</b>' to add new date.</h4>
    <a class="btn btn-default js-toggle-newDate-form" href="#">
      <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
    </a>
    <div id="newDate_form" class="hidden_div jumbotron">
      <form class="js-save-newDate-form form-group-sm">
        <div class="form-group">
          <label for="dayJob">Day</label>
          <input type="text" class="form-control" id="dayJob" placeholder="Day format: dd-MM-yyyy" required
          data-fv-notempty-message="The day is required">
        </div>
        <div class="form-group">
          <label for="dateTime">Time</label>
          <input type="text" class="form-control" id="dateTime" placeholder="Time format: hh:mm" required
          data-fv-notempty-message="The time is required">
        </div>
        <div class="form-group">
          <label for="note">Note</label>
          <input type="text" class="form-control" id="note" placeholder="Note" required
          data-fv-notempty-message="Note">
        </div>
      </form>
    </div>
  {{/if}}
</template>

1 个答案:

答案 0 :(得分:0)

MongoDB supports storing Date objects natively, I'd do that and use a template helper to display it the way you want it. The advantage to this is that querying on Date objects is much easier than string representations of dates.

Here's an example helper:

Template.registerHelper( 'humanDate', ( timestamp ) => {
  if ( timestamp ) {
    var time   = moment( timestamp ),
        format = 'DD-MM-YYYY';
    return time.format( format );
  }
});

You'll need the momentjs package: meteor add momentjs:moment for that to work.

Then you can use the template helper to display your date:

{{humanDate dateTime}}

Provided that dateTime is an actual date object. You can create a new Date when you go to insert into your Dates collection with a little refactoring.