0

我有一个 Meteor Collection,我在其中存储日期和时间(我的工作时间表)。时间保存为秒。

当我在模板中展示它们时,我所做的只是

Days.find({})

我可以像这样在我的模板中使用它:

<template name="calendar">
  {{#each days}}
    <p>
      {{> day}}
    </p>
  {{/each}}
</template>

<template name="day">
  <p>
    {{date}} - {{time}}
  </p>
</template>

现在“时间”以秒为单位,它将显示类似 30240(以秒为单位的时间),但我真正想要显示的是 8h 24m。如何向该模板添加一个计算小时和分钟的函数?

4

1 回答 1

1

将您的时间转换为字符串

您可以在一天模板中添加一个助手,将其转换为您想要的形式:

Template.day.helpers({
    niceTime:function() {

        var timeInMs = this.time; //'this' is the current data context
        var datetime = new Date(timeInMs); //convert this to a date object
        return datetime.toLocaleTimeString; //return the time in a locale string
    }
});

然后在您的模板中使用{{niceTime}}而不是{{time}}

这也取决于您将时间存储为什么。如果它在 javascript unix 时间中存储为自 1970 年以来的毫秒数或从一天开始的毫秒数。如果以秒为单位,则需要先将其乘以 1000。如果您.getTime()以前将它存储在流星中时得到它,则可以按原样使用上述内容。

如果您从一天开始以秒为单位存储,则将 1970 年(unix 时间开始)的毫秒添加到您的时间。

var today = new Date();
var timeInMs = (this.time*1000) + new Date(today.getFullYear(),today.getMonth(),today.getDate()).toTime();

将您的日期存储为日期对象

总而言之,将日期存储为Date对象可能会更好。然后,您可以根据需要获取日期toLocaleDateString()或超时toLocaleTimeString(),并根据浏览器的位置将其调整为不同的时区(因为它的核心是将日期和时间存储在 UTC 中的 unixtime 中)。此外,您不必单独存储时间。

于 2013-05-12T10:21:14.333 回答