javadatetimetimetimeofday

convert time variable to hh:mm format in java


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 .


Solution

  • You could write a method that creates proper random hours and random minutes, then construct a java.time.LocalTime of them and return a desired String representation.

    Here's an example:

    public static String createRandomTime() {
        // create valid (in range) random int values for hours and minutes
        int randomHours = ThreadLocalRandom.current().nextInt(0, 23);
        int randomMinutes = ThreadLocalRandom.current().nextInt(0, 59);
        // then create a LocalTime from them and return its String representation
        return LocalTime.of(randomHours, randomMinutes).format(
                                // using a desired pattern
                                DateTimeFormatter.ofPattern("HH:mm")
        );
    }
    

    Executing that method ten times in a main like this

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(createRandomTime());
        }
    }
    

    will produce an output like (not necessarily equal to)

    08:16
    07:54
    17:15
    19:41
    14:24
    12:00
    12:33
    11:00
    09:11
    02:33
    

    Please note that the int values and corresponding LocalTime created from them will not change if you just want another format. You can easily switch the pattern to another one (maybe make the pattern String a parameter of the method). E.g. you could make it "hh:mm a" for Strings like 10:23 AM.