下面的代码给出了当前时间。但是它并没有告诉我们毫秒。
public static String getCurrentTimeStamp() {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
我有一个日期,格式是YYYY-MM-DD HH:MM:SS(2009-09-22 16:47:08)。
但是我想以YYYY-MM-DD HH:MM:SS的格式检索当前时间。MS(2009-09-22 16:47:08.128,其中128为毫秒)。
SimpleTextFormat可以很好地工作。这里最低的时间单位是秒,但我怎么也能得到毫秒呢?
java.time
问题和接受的答案使用java.util.Date和SimpleDateFormat,这在2009年是正确的做法。2014年3月,java。SimpleDateFormat已经被现代日期时间API所取代。从那时起,强烈建议停止使用遗留的日期-时间API。
使用java解决方案。time,现代date-time API:
LocalDateTime.now(ZoneId.systemDefault())
.format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS"))
关于这个解决方案的一些要点:
将ZoneId. systemdefault()替换为适用的ZoneId,例如ZoneId.of("America/New_York")。
如果当前日期-时间在系统的默认时区(ZoneId)中是必需的,则不需要使用LocalDateTime#now(ZoneId zone);相反,您可以使用LocalDateTime#now()。
你可以用y代替u,但我更喜欢u。
演示:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
class Main {
public static void main(String args[]) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
// Replace ZoneId.systemDefault() with the applicable ZoneId e.g.
// ZoneId.of("America/New_York")
LocalDateTime ldt = LocalDateTime.now(ZoneId.systemDefault());
String formattedDateTimeStr = ldt.format(formatter);
System.out.println(formattedDateTimeStr);
}
}
在我的系统时区欧洲/伦敦运行示例的输出:
2023-01-02 09:53:14.353
在线演示
从Trail: Date Time了解更多关于现代Date-Time API的信息。