Java examples for java.util:Time
Makes a time String in the format HH:MM:SS from a Date.
//package com.java2s; import java.util.Calendar; public class Main { /**/*from w w w . j a v a 2 s . c om*/ * Makes a time String in the format HH:MM:SS from a Date. If the seconds * are 0, then the output is in HH:MM. * * @param date * The Date * @return A time String in the format HH:MM:SS or HH:MM */ public static String toTimeString(java.util.Date date) { if (date == null) return ""; Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return (toTimeString(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND))); } /** * Makes a time String in the format HH:MM:SS from a separate ints for hour, * minute, and second. If the seconds are 0, then the output is in HH:MM. * * @param hour * The hour int * @param minute * The minute int * @param second * The second int * @return A time String in the format HH:MM:SS or HH:MM */ public static String toTimeString(int hour, int minute, int second) { String hourStr; String minuteStr; String secondStr; if (hour < 10) { hourStr = "0" + hour; } else { hourStr = "" + hour; } if (minute < 10) { minuteStr = "0" + minute; } else { minuteStr = "" + minute; } if (second < 10) { secondStr = "0" + second; } else { secondStr = "" + second; } if (second == 0) return hourStr + ":" + minuteStr; else return hourStr + ":" + minuteStr + ":" + secondStr; } }