The output you are getting is as expected because a string is parsed into java.util.Date
using a SimpleDateFormat
which defaults the date-time to January 1, 1970, 00:00:00 GMT
.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws ParseException {
String text = "09:30:00";
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date date = sdf.parse(text);
System.out.println(date);
}
}
The output in my timezone (Europe/London):
Thu Jan 01 09:30:00 GMT 1970
Note that 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. The java.util
date-time API and their formatting API, SimpleDateFormat
are not only outdated but also error-prone because of many such things. It is recommended to stop using them completely and switch to the modern date-time API1.
Given below are a couple of options:
- Recommended: Use
LocalTime
which truly represents time.
@DateTimeFormat(pattern = "HH:mm:ss")
private LocalTime time;
- Dirty way: Declare your field as a
String
and parse it in your business logic making it error-prone and dirty.
private String time;
I strongly recommend NOT to go with the second option.
A quick demo using LocalTime
:
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String text = "9:30:00";
// The optional part can be put inside square bracket
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("H:m[:s]", Locale.ENGLISH);
LocalTime time = LocalTime.parse(text, dtfInput);
// Default implementation of LocalTime#toString omits the seconds part if it is zero
System.out.println(time);
// Custom output
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("HH:mm:ss", Locale.ENGLISH);
String formatted = dtfOutput.format(time);
System.out.println(formatted);
}
}
Output:
09:30
09:30:00
Learn more about the modern date-time API from Trail: Date Time.
1. 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.