What time is it? in Java


The problem

What number of instances have we been requested this easy query in our day by day lives by household, buddies and strangers alike?

On this problem you check out your watch and reply this query in correct English. Typically you will have your watch in 24h format and others in 12h. The AM/PM a part of the time is at all times disregarded because the asker is aware of whether or not it’s morning or afternoon.

Necessities:
  1. Thoughts the punctuation for the complete hours; o’clock is written as one phrase.
  2. Spacing between particular person phrases is strictly restricted to at least one area. Cardinal numbers higher than 20 are hyphenated (e.g. “twenty-one”).
  3. Enter is at all times going to be a non-null string within the format d{2}:d{2}(s?[ap]m)?
  4. Each 12h and 24h enter could also be current. In case of 12h enter disregard the am/pm half.
  5. Do not forget that in 24h midnight is denoted as 00:00.
  6. There might or will not be an area between the minutes and the am/pm half in 12h format.
Examples:
toHumanTime("05:28 pm"); // twenty-eight minutes previous 5
toHumanTime("12:00");    // twelve o'clock
toHumanTime("03:45am");  // quarter to 4
toHumanTime("07:15");    // quarter previous seven
toHumanTime("23:30");    // half previous eleven
toHumanTime("00:01");    // one minute previous twelve
toHumanTime("17:51");    // 9 minutes to 6 

The answer in Java code

Possibility 1:

public class TimeFormatter {

  personal ultimate static String[] NUMBERS = {
    "o'clock",
    "one", "two", "three", "4", "5", 
    "six", "seven", "eight", "9", "ten",
    "eleven", "twelve", "13", "fourteen", "quarter", 
    "sixteen", "seventeen", "eighteen", "nineteen", "twenty",
    "twenty-one", "twenty-two", "twenty-three", "twenty-four", "twenty-five", 
    "twenty-six", "twenty-seven", "twenty-eight", "twenty-nine", "half" };
    
  personal static String minuteStr(ultimate int m) 
  
  personal static int hr12(ultimate int h) {
    int hr = h % 12;
    return hr == 0 ? 12 : hr;
  }
  
  public static String toHumanTime(ultimate String time) {
    ultimate String[] elements = time.cut up("[s:aApP]");
    ultimate int hr = Integer.valueOf(elements[0]), min = Integer.valueOf(elements[1]);
    if (min == 0) return String.format("%s %s", NUMBERS[hr12(hr)], NUMBERS[0]);    
    if (min <= 30) return String.format("%s previous %s", minuteStr(min), NUMBERS[hr12(hr)]);
    return String.format("%s to %s", minuteStr(60 - min), NUMBERS[hr12(hr+1)]);
  }
  
}

Possibility 2:

public class TimeFormatter {
    public static String toHumanTime(String time) {
        String stringH = time.replaceAll(":.+$", "");
        String stringM = time.replaceAll("^(d.)", "");
        String stringM1 = stringM.replaceAll("D", "");
        return printWords(Integer.valueOf(stringH), Integer.valueOf(stringM1));
    }

    personal static String printWords(int h, int m) {
        String nums[] = {"twelve", "one", "two", "three", "4", "5", "six", "seven", "eight", "9", "ten",
                "eleven", "twelve", "13", "fourteen", "fifteen" ,"sixteen", "seventeen", "eighteen", "nineteen", "twenty",
                "twenty-one", "twenty-two", "twenty-three", "twenty-four", "twenty-five", "twenty-six",
                "twenty-seven", "twenty-eight", "twenty-nine"};

        if (m == 0) return nums[h%12] + " o'clock";
        else if (m == 1) return "one minute previous " + nums[h%12];
        else if (m == 59) return "one minute to " + nums[(h % 12) + 1];
        else if (m == 15) return "quarter previous " + nums[h%12];
        else if (m == 30) return "half previous " + nums[h%12];
        else if (m == 45) return "quarter to " + nums[(h % 12) + 1];
        else if (m <= 30) return nums[m] + " minutes previous " + nums[h%12];
        //  else if (m > 30)
        return nums[60 - m] + " minutes to " + nums[(h % 12) + 1];
    }
}

Check instances to validate our resolution

import static org.junit.Assert.*;
import org.junit.Check;

public class TimeFormatterTest {

    @Check
    public void basicTests() {
        assertEquals("twenty-eight minutes previous 5", TimeFormatter.toHumanTime("05:28 pm"));
        assertEquals("twelve o'clock", TimeFormatter.toHumanTime("12:00"));
        assertEquals("quarter to 4", TimeFormatter.toHumanTime("03:45am"));
        assertEquals("quarter previous seven", TimeFormatter.toHumanTime("07:15"));
        assertEquals("half previous eleven", TimeFormatter.toHumanTime("23:30"));
        assertEquals("one minute previous twelve", TimeFormatter.toHumanTime("00:01"));
        assertEquals("9 minutes to 6", TimeFormatter.toHumanTime("17:51"));
    }
}

Further take a look at instances

import org.junit.Check;

import java.util.Random;
import java.util.stream.IntStream;

import static org.junit.Assert.assertEquals;

public class TimeFormatterTest {

    personal static ultimate String[] cardinals = new String[]{
        "one","two","three","4","5","six","seven","eight","9","ten",
        "eleven","twelve","13","fourteen","quarter","sixteen","seventeen","eighteen","nineteen","twenty"
    };
    personal static ultimate Random random = new Random(System.currentTimeMillis());

    personal String format(int h, int m) {
        boolean is24format = random.nextBoolean();
        boolean isAm = random.nextBoolean();
        String extraSpace = random.nextBoolean() ? " " : "";
        String a = "";
        if (is24format) {
            if (!isAm) h += 12;
            if (h == 24) h = 0;
        } else {
            a = extraSpace + (isAm ? "am" : "pm");
        }
        return String.format("%02d:%02dpercents", h, m, a);
    }

    personal String calcMinutes(int m) {
        StringBuilder minutes = new StringBuilder();
        if (m <= 20) {
            minutes.append(cardinals[m-1]);
        } else {
            String hyphenated = String.be a part of("-", cardinals[19], cardinals[m-21]);
            minutes.append(hyphenated);
        }
        minutes.append(m == 15 ? "" : (" minute" + (m == 1 ? "" : "s")));
        return minutes.toString();
    }

    @Check
    public void basicTests() {
        assertEquals("twenty-eight minutes previous 5", TimeFormatter.toHumanTime("05:28 pm"));
        assertEquals("twelve o'clock", TimeFormatter.toHumanTime("12:00"));
        assertEquals("quarter to 4", TimeFormatter.toHumanTime("03:45am"));
        assertEquals("quarter previous seven", TimeFormatter.toHumanTime("07:15"));
        assertEquals("half previous eleven", TimeFormatter.toHumanTime("23:30"));
        assertEquals("one minute previous twelve", TimeFormatter.toHumanTime("00:01"));
        assertEquals("9 minutes to 6", TimeFormatter.toHumanTime("17:51"));
    }

    @Check
    public void shouldTranslateCorrectlyTimeStrings() {
        IntStream.rangeClosed(1,12).forEach(hour -> {
            String translatedHour = cardinals[hour-1];
            String expectedFull = translatedHour + " o'clock";
            assertEquals(expectedFull, TimeFormatter.toHumanTime(format(hour, 0)));

            String expectedPastQuarter = "quarter previous " + translatedHour;
            assertEquals(expectedPastQuarter, TimeFormatter.toHumanTime(format(hour, 15)));

            String expectedHalf = "half previous " + translatedHour;
            assertEquals(expectedHalf, TimeFormatter.toHumanTime(format(hour, 30)));

            String translatedNextHour = cardinals[hour%12];
            String expectedToQuarter = "quarter to " + translatedNextHour;
            assertEquals(expectedToQuarter, TimeFormatter.toHumanTime(format(hour, 45)));

            // minutes previous ...[hour]
            IntStream.of(1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,17,18,19,20,21,22,23,24,25,26,27,28,29)
                .mapToObj(m -> {
                    String minutes = calcMinutes(m);
                    return new Object[]{minutes + " previous " + cardinals[hour-1], m};
                })
                .forEachOrdered(anticipated ->
                    assertEquals(anticipated[0], TimeFormatter.toHumanTime(format(hour, (Integer)anticipated[1])))
                );

            // minutes to ...[nextHour]
            IntStream.of(31,32,33,34,35,36,37,38,39,40,41,42,43,44,46,47,48,49,50,51,52,53,54,55,56,57,58,59)
                .mapToObj(m -> {
                    String minutes = calcMinutes(60-m);
                    return new Object[]{minutes + " to " + cardinals[hour%12], m};
                })
                .forEachOrdered(anticipated ->
                    assertEquals(anticipated[0], TimeFormatter.toHumanTime(format(hour, (Integer)anticipated[1])))
                );
        });
    }
}

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles