Friday, July 13, 2012

Randomly generating a date before or after today



I was recently building a calendar type app for a client and needed to test out the placement of items on the calendar. Unfortunately their test data returned all items with the exact same date. So I wrote a little bit of code that would randomly replace the date in the data with AM PM (the calendar data didn't have a time just whether or not it was in the morning or afternoon and randomly assign a date within a week both before and after today.



 private String generateRandomAmOrPm() {  
         final Random myRandom = new Random();  
         boolean amOrPm=        myRandom.nextBoolean();  
         if (amOrPm) {  
              return "AM";  
         } else {  
              return "PM";  
         }  
      }  
      private int generateRandomDate() {  
            final Random myRandom = new Random();  
              boolean plusOrMinus=        myRandom.nextBoolean();  
              int dateToMove = myRandom.nextInt(6); // plus or minus 6 days  
              if (plusOrMinus) {  
                   return 0-dateToMove;  
              } else {  
                   return dateToMove;  
              }  
      }  

No comments:

Post a Comment