我一直在研究一个在两天之间动态创建date/time
值的脚本。但是我想限制它如下:
if appointment.status === "today"
:设置now
(开始)和工作日的end
(结束)之间的范围,即今天到现在的18:00
if appointment.status === "pending"
:设置明天(start) + 1 week
(结束)的范围,但要记住工作日i.e. 08:00-17:00...
,以便下周Tuesday 13:00
完成后,我想将var date
转换为timestamp.
到目前为止,这是我的代码:
if (appointment.status === "today") { appointment.timestamp = (function() { var a = randomTime(new Date("10-10-2015 10:30"), new Date("12-10-2015 02:10")); return a })(); } else if (appointment.status === "pending") { appointment.timestamp = (function() { var a = randomTime(new Date("10-10-2015 10:30"), new Date("12-10-2015 02:10")); return a })(); } function randomTime(start, end) { var diff = end.getTime() - start.getTime(); var new_diff = diff * Math.random(); var date = new Date(start.getTime() + new_diff); return date; }
答案 0 :(得分:1)
var start = new Date();
var end = new Date();
if (appointment.status === "today") {
end.setHours(18);
end.setMinutes(0);
} else if (appointment.status === "pending") {
start.setDate(start.getDate() + 1);
end.setDate(end.getDate() + 7);
}
start = restrictTimeToWorkHours(start);
end = restrictTimeToWorkHours(end);
appointment.timestamp = Math.floor(randomTime(start, end) / 1000);
function randomTime(start, end) {
var diff = end.getTime() - start.getTime();
var new_diff = diff * Math.random();
return new Date(start.getTime() + new_diff);
}
function restrictTimeToWorkHours(date) {
if (date.getHours() < 8) {
date.setHours(8);
date.setMinutes(0);
}
if (date.getHours() > 16) {
date.setHours(16);
date.setMinutes(0);
}
return date;
}
这里要记住的关键是Math.floor(randomTime(start, end) / 1000);
。你说你想要它在时间戳中,所以我认为你想要一个Unix时间戳。 Unix Timestasmp以秒为单位,而Date.getTime()
以毫秒为单位,因此我们需要除以1000来获得秒数
答案 1 :(得分:1)
查找日期库或为每个操作创建自己的日期转换功能并组合它们。
endOfDay(time)
getRandomTimeBetween(startTime, endOfDay(startTime))
isWorkingDay(time)
// etc.
对于第二种情况,您可以分两步完成:在范围内选择一个随机日,然后在当天的工作时间内选择一个随机时间。
将其分解为简单的逻辑操作,您可以单独测试每个函数,并且您的代码看起来不错且可读。