简体   繁体   中英

Java: Separate Time Digits

I'm trying to separate each number in an hh:mm type of setup into individual digits. So if the time was 8:24, I would have [0, 8, 2, 4]. How would I do that?

Once you get the hour and minute from your Date object, you can use the mod and % operators to calculate the individual digits. http://mindprod.com/jgloss/modulus.html

You need to format your input text with HH:mm date pattern, remove all non-numeric characters and finally split string into characters.

String inputTime = "8:24";
DateFormat df = new SimpleDateFormat("HH:mm");
String formattedInputTime = df.format(df.parse(inputTime));

String timeDigits = formattedInputTime.replaceAll("[^\\d]", "");

char[] timeDigitTokens = timeDigits.toCharArray();
for (char timeDigitToken : timeDigitTokens) {
    System.out.println(timeDigitToken);
}

Compile and run working code here.

No need to remove non-numeric characters as suggested above, just don't put them in the formatted date to begin with. Also, there's no need for the toCharArray to be called, as you can get at each character directly via String.charAt method:

String s = new SimpleDateFormat("mmss").format(new Date());
System.out.println(s.charAt(0));
System.out.println(s.charAt(1));
System.out.println(s.charAt(2));
System.out.println(s.charAt(3));

Based on Chris Nava's idea (upvote his answer first) and assuming you want int digits instead of char :

public class TimeSplit {

  public static void main(String[] args) throws ParseException {
    printSplit("8:24"); // [0, 8, 2, 4]
    printSplit("10:22"); // [1, 0, 2, 2]
    printSplit("13:57"); // [0, 1, 5, 7] because of 12h
  }

  private static void printSplit(String time) throws ParseException {
    System.out.println(time + " -> " + Arrays.toString(split(time)));
  }

  private static int[] split(String time) throws ParseException {
    DateFormat fmt = new SimpleDateFormat("hh:mm"); // 12h, use HH for 24h
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(fmt.parse(time));
    return split(calendar);
  }

  private static int[] split(Calendar time) {
    int hours = time.get(Calendar.HOUR); // 12h, use HOUR_OF_DAY for 24h
    int minutes = time.get(Calendar.MINUTE);

    int[] digits = new int[4];
    digits[0] = hours / 10;
    digits[1] = hours % 10;
    digits[2] = minutes / 10;
    digits[3] = minutes % 10;
    return digits;
  }
}

Output:

8:24 -> [0, 8, 2, 4]
10:22 -> [1, 0, 2, 2]
13:57 -> [0, 1, 5, 7]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM