根据if-else子句创建随机UNIX时间戳

时间:2016-03-02 17:57:26

标签: javascript timestamp

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

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

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

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

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

1 个答案:

答案 0 :(得分:1)

这类似于另一个问题(Generate random date between two dates and times in 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)