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*.
Solution using java.time
, the modern Date-Time API:
import java.time.LocalTime;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
LocalTime time = LocalTime.now(ZoneId.of("Asia/Jerusalem"));
System.out.println(time);
}
}
Output from a sample run:
15:06:50.207521
ONLINE DEMO
If you want the format to be restricted to HH:mm
, a couple of ways to to do so are:
- Truncating the
LocalTime
to ChronoUnit.MINUTES
.
- Using
DateTimeFormatter
with the pattern, HH:mm
.
Demo:
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalTime timeHourMinute = LocalTime.now(ZoneId.of("Asia/Jerusalem"))
.truncatedTo(ChronoUnit.MINUTES);
System.out.println(timeHourMinute);
// Alternatively
LocalTime time = LocalTime.now(ZoneId.of("Asia/Jerusalem"));
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm", Locale.ENGLISH);
String strTime = dtf.format(time);
System.out.println(strTime);
}
}
Output from a sample run:
16:01
16:01
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
* 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.