您得到的输出与预期的一样,因为使用SimpleDateFormat 将字符串解析为java.util.Date,默认日期时间为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);
}
}
我的时区(欧洲/伦敦)的输出:
Thu Jan 01 09:30:00 GMT 1970
注意java.util.Date 对象不是像modern date-time types 那样的真实日期时间对象;相反,它表示自称为“纪元”的标准基准时间以来的毫秒数,即January 1, 1970, 00:00:00 GMT(或 UTC)。当您打印java.util.Date 的对象时,它的toString 方法会返回JVM 时区中的日期时间,从这个毫秒值计算得出。如果您需要在不同的时区打印日期时间,则需要将时区设置为 SimpleDateFormat 并从中获取格式化字符串。 java.util 日期时间 API 及其格式化 API SimpleDateFormat 不仅已过时,而且由于许多此类事情而容易出错。建议完全停止使用,改用modern date-time API1。
以下是几个选项:
-
推荐:使用真正代表时间的
LocalTime。
@DateTimeFormat(pattern = "HH:mm:ss")
private LocalTime time;
-
肮脏的方式:将您的字段声明为
String,并在您的业务逻辑中对其进行解析,使其容易出错且很脏。
private String time;
我强烈建议不选择第二个选项。
使用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);
}
}
输出:
09:30
09:30:00
从 Trail: Date Time 了解有关现代日期时间 API 的更多信息。
1.出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7。如果您正在为Android 项目和您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring 和 How to use ThreeTenABP in Android Project。