它给出了当前的日期、月份、年份和时间。但我只需要得到
从现在开始的当前时间。
java.util.Date 对象不像modern Date-Time types 那样是真正的日期时间对象;相反,它表示自称为“纪元”的标准基准时间以来的毫秒数,即January 1, 1970, 00:00:00 GMT(或 UTC)。当您打印java.util.Date 的对象时,它的toString 方法会返回JVM 时区中的日期时间,从这个毫秒值计算得出。如果您需要在不同的时区打印日期时间,则需要将时区设置为 SimpleDateFormat 并从中获取格式化字符串,例如
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));
为了获得准确的时间,您只需将 (a) yyyy-MM-dd'T'HH:mm:ss.SSSXXX 替换为 hh:mm a 和 (b) America/New_York 替换为适用的时区。
但是,java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用,改用modern Date-Time API*。
使用现代 API java.time 的解决方案:
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);
}
}
输出:
11:59:07.443868
11:59 AM
从Trail: Date Time了解更多关于java.timemodern Date-Time API*的信息。
* 出于任何原因,如果您必须坚持使用 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。