java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time
, the modern Date-Time API: Create a LocalTime
with hour
and minute
, and get the value of LocalTime#toString
to be set to etTime
.
Demo:
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
// Test
String text = getTimeString(6, 30);
System.out.println(text);
text = getTimeString(18, 30);
System.out.println(text);
}
static String getTimeString(int hour, int minute) {
return LocalTime.of(hour, minute).toString();
}
}
Output:
06:30
18:30
ONLINE DEMO
The modern Date-Time API is based on ISO 8601 and thus the LocalTime#toString
returns the string in ISO 8601 format (which is also your desired format).
Learn more about the modern Date-Time API from Trail: Date Time.
Just for the sake of completeness:
Just for the sake of completeness, given below is the solution using the legacy API:
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
// Test
String text = getTimeString(6, 30);
System.out.println(text);
text = getTimeString(18, 30);
System.out.println(text);
}
static String getTimeString(int hour, int minute) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
return new SimpleDateFormat("HH:mm").format(calendar.getTime());
}
}
Output:
06:30
18:30
ONLINE DEMO
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.