2

How do I create a random UNIX timestamp using JavaScript:

  • Between now and the end of the working day (i.e. today between 08:00-17:00) if appointment.status === "today".

  • From tomorrow + 1 week but keeping in mind the working day (so it can be next week Tuesday 13:00, keeping in mind the working day i.e. 08:00-17:00) if appointment.status === "pending".

This is what I have done so far:

if(appointment.status === "today") {
  appointment.timestamp = (function() {
    return a
  })();         
} else if(appointment.status === "pending") {       
  appointment.timestamp = (function() {
    return a
  })();                 
}
methuselah
  • 12,766
  • 47
  • 165
  • 315

1 Answers1

2

This is similar to another question (Generate random date between two dates and times in Javascript) but to handle the "pending" appointments you'll also need a way to get a day between tomorrow and a week from tomorrow.

This function will return a random timestamp between 8:00 and 17:00 on the date that is passed to it:

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();
}

To get a random timestamp today between 08:00 and 17:00 today you could do:

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)

This function will return a random date between tomorrow and a week from tomorrow for the date that is passed to it:

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());
}

To get a random timestamp between 08:00 and 17:00 on a random day between tomorrow and a week from tomorrow, you could do:

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)
Community
  • 1
  • 1
twernt
  • 20,271
  • 5
  • 32
  • 41