1

I'm looking to generate a random time. Right now I'm using chance.js to give me what is basically a random time but it's a bit broken. Here's my code:

$(".time").each(function(){
    var hourSet = chance.hour(),
    minuteSet = chance.minute(),
    amPm = chance.ampm();
    $(this).html(hourSet+':'+minuteSet+" "+amPm);
});

This spits out things like:

2:26 pm
8:1 pm
5:50 pm

The issue is that the minute generator sometimes generates single digit minutes like 8:1 pm. I want it to generate 8:01 pm if the minute is less than 10.

I was thinking of using moment.js to parse a timestamp that's randomly generated by chance.js but its complete overkill. It must be possible with what I have here.

potashin
  • 44,205
  • 11
  • 83
  • 107
gschervish
  • 293
  • 2
  • 5
  • 15
  • possible duplicate of [Add padding 0 before single character in javascript clock](http://stackoverflow.com/questions/11929925/add-padding-0-before-single-character-in-javascript-clock) – Felix Kling Dec 04 '13 at 18:57
  • possible duplicate of [How can I create a Zerofilled value using JavaScript?](http://stackoverflow.com/questions/1267283/how-can-i-create-a-zerofilled-value-using-javascript) – Lynn Crumbling Dec 04 '13 at 18:57

1 Answers1

2

Got it based off of checking value with if statement.

$(".time").each(function(){
    var hourSet = chance.hour(),
    minuteSet = chance.minute(),
    amPm = chance.ampm();
    if (parseInt(minuteSet) < 10) {
        minuteSet = "0" + minuteSet;
    };
    $(this).html(hourSet+':'+minuteSet+" "+amPm);
});
gschervish
  • 293
  • 2
  • 5
  • 15