I'm a beginner in java and I with my code below I can generate a random time in "hh:mm:ss" format . I have no idea how to tweak my code to display time in "hh:mm" format as I am not familiar with the
Date and Time java libraries . I have checked posts here like converting time from hh:mm:ss to hh:mm in java but it does not help here .
import java.util.Random;
import java.sql.Time;
final Random random = new Random();
final int millisInDay = 24*60*60*1000;
Time time = new Time((long)random.nextInt(millisInDay));
I have also tried :
// creates random time in hh:mm format for 0-12 hours but I want the full 24 hour timeline
public static String createRandomTime() {
DateFormat format = new SimpleDateFormat("h.mm aa");
String timeString = format.format(new Date()).toString();
return timeString;
}
I would appreciate your help .
You could write a method that creates proper random hours and random minutes, then construct a
java.time.LocalTimeof them and return a desiredStringrepresentation.Here's an example:
Executing that method ten times in a
mainlike thiswill produce an output like (not necessarily equal to)
Please note that the
intvalues and correspondingLocalTimecreated from them will not change if you just want another format. You can easily switch the pattern to another one (maybe make the patternStringa parameter of the method). E.g. you could make it"hh:mm a"forStrings like10:23 AM.