基于 if-else 子句创建随机 UNIX 时间戳

Create random UNIX timestamp based on if-else clause

本文关键字:UNIX 时间戳 随机 创建 if-else 子句 基于      更新时间:2023-09-26

如何使用JavaScript创建随机UNIX时间戳:

  • 现在到工作日结束(即今天 08:00-17:00 之间),如果appointment.status === "today"

  • 明天 + 1 周开始,但请记住工作日(所以可以是下周星期二 13:00,请记住工作日,即 08:00-17:00),如果appointment.status === "pending"

这是我到目前为止所做的:

if(appointment.status === "today") {
  appointment.timestamp = (function() {
    return a
  })();         
} else if(appointment.status === "pending") {       
  appointment.timestamp = (function() {
    return a
  })();                 
}

这类似于另一个问题(在Javascript中生成两个日期和时间之间的随机日期),但要处理"待处理"约会,您还需要一种方法来获取明天明天一周之间的一天。

此函数将在传递给它的日期的 8:00 到 17:00 之间返回一个随机时间戳:

var randomTimeInWorkday = function(date) {
    var begin = date;
    var end = new Date(begin.getTime());
    begin.setHours(8,0,0,0);
    end.setHours(17,0,0,0);
    return Math.random() * (end.getTime() - begin.getTime()) + begin.getTime();
}

要获取今天 08:00 到 17:00 之间的随机时间戳,您可以执行以下操作:

var today = new Date();
var timestamp = randomTimeInWorkday(today);
console.log(timestamp); // 1457033914204.1597
console.log(new Date(timestamp)); // Thu Mar 03 2016 14:38:34 GMT-0500 (EST)

此函数将返回从明天到从明天起一周之间的随机日期,用于传递给它的日期:

var randomDayStartingTomorrow = function(date) {
  var begin = new Date(date.getTime() + 24 * 60 * 60 * 1000); 
  var end = new Date(begin.getTime());
  end.setDate(end.getDate() + 7);
  return new Date(Math.random() * (end.getTime() - begin.getTime()) + begin.getTime());
}

要在明天和从明天开始的一周之间的随机日期获取 08:00 到 17:00 之间的随机时间戳,您可以执行以下操作:

var today = new Date();
var randomDay = randomDayStartingTomorrow(today);
var timestamp = randomTimeInWorkday(randomDay);
console.log(timestamp); // 1457194668335.3162
console.log(new Date(timestamp)); // Sat Mar 05 2016 11:17:48 GMT-0500 (EST)