我正在尝试找到处理餐厅营业时间的最佳方式。复杂性是由于以下事实:
- 地点可能在同一天开放多次(例如 7:00-14:30、18:30-22:00)
- 有时关门时间会超过午夜(例如 19:00-2:00)
- 并非每天都有相同的时间
因此,一个好的方法似乎是注册一周中每一天的打开/关闭时间数组,格式为:自一周开始以来的秒数
。这是一个例子
{
"address": "street 1, city, postcode",
"hours" : {
"mon" : [
{
"opened" : 25200, // 07:00
"closed" : 52200 // 14:30
}
],
"tue" : [
{
"opened" : 111600, // 07:00
"closed" : 138600 // 14:30
},
{
"opened" : 153000, // 18:30
"closed" : 180000 // 02:00 (of the day after)
}
],
...
}
}
(在模型中,我使用 a small piece of code I wrote 渲染了一个静态变量来为每个字段执行自动表单下拉菜单)
在我看来,整个星期的营业时间是这样呈现的:
Monday: {{#each hours.mon}}
{{#if @index ">" 0}}<br />{{/if}} // this just breaks the second array item in a new line
{{getOpeningTime opened}} - {{getOpeningTime closed}}
{{/each}}
<br/>
Tuesday: ...
getOpeningTime
是一个模板助手,它使用 moment.js
以 HH:mm 格式返回时间:
getOpeningTime: function(seconds) {
return moment().startOf('day').seconds(seconds).format('HH:mm');
}
到目前为止一切都很好 - 虽然我仍然不确定这是否是正确的方法
现在,我试图在用户查看页面时通知用户餐厅是否开门。到目前为止,这是我写的内容:
openedOrClosed: function() {
now = moment();
ddd = now.format('ddd').toLowerCase(); // I now I will look into the field hours.day - the first three letters all lowercase
day = now.day();
day = (day === 0 ? 7 : day); // This is just a conversion I do because I want to have Sunday at the end of the week
seconds = now.clone().diff(now.clone().startOf('day'), 'seconds') + (86400 * day) - 86400; // Minutes since midnight in Momentjs (http://stackoverflow.com/a/25390707/1435476) plus the sum of all the other days of the week to work out the global seconds since the beginning of the week
query = {};
query._id = this._id;
// here I have available all I need. but I'm not sure how to build the query
if (Restaurants.find(query).count() > 0) {
return "Opened";
} else {
return "Closed";
}
}
最佳答案
首先:处理日期和时间是一项挑战 :)。
我认为您的“自一周开始以来的秒数”格式没有必要。 Momentjs 可以将“现在”解析为日期和小时(以及更多)。
您还应该考虑圣诞节等异常(exception)情况。除此之外,一家餐厅一天可以营业多次(例如九点到两点,五点到十一点)。
我会选择这样的东西:
restaurantname:{
//special days array of objects
specialdays:
[{date: date,
openinghours:
//again array of objects
[{start: sometime, end: sometime},
{start: somtime, end: sometime},
//etc
]
}]
},
normaldays: {mon: //openinghours like above, again array of objects with start and end, tue, wed etc}
之后您可以先检查一下:今天是不是特别的日子?如果是 => 检查当前时间是否在开始之后和结束之前(遍历对象数组)。 否则,如果不是特殊的日子,请检查特定的“正常日子”并执行相同的操作。
我认为切换是理想的选择。你可以先从具体到一般,让你的条件先通过具体案例。
这只是一个大纲,我知道它具有挑战性 :)。
希望这有助于...
关于Mongodb 处理开放时间以及如何找到我们的地方是否开放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32935753/