It gives the current date,month,year and time.But i need to get only
the current time from this.
The java.util.Date
object is not a real Date-Time object like the modern Date-Time types; rather, it represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT
(or UTC). When you print an object of java.util.Date
, its toString
method returns the Date-Time in the JVM's timezone, calculated from this milliseconds value. If you need to print the Date-Time in a different timezone, you will need to set the timezone to SimpleDateFormat
and obtain the formatted string from it e.g.
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println(sdf.format(date));
In order to get just the time, you just need to replace (a) yyyy-MM-dd'T'HH:mm:ss.SSSXXX
with hh:mm a
and (b) America/New_York
with the applicable timezone.
However, 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 API:
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Replace JVM's timezone i.e. ZoneId.systemDefault() with the applicable
// timezone e.g. ZoneId.of("Europe/London")
LocalTime time = LocalTime.now(ZoneId.systemDefault());
// Print the default format i.e. the value of time.toString()
System.out.println(time);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
String formattedTime = dtf.format(time); // Alternatively, time.format(dtf)
System.out.println(formattedTime);
}
}
Output:
11:59:07.443868
11:59 AM
Learn more about java.time
, 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.