我有这段代码:
SimpleDateFormat sDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
我知道这段代码返回时间中的小时、分钟和秒。如何获取毫秒和微秒?
因为Date存储自1970年1月1日以来的毫秒数,所以您无法获得微秒。对于毫秒,请使用javadoc中记录的S
。
要获取微秒时间,唯一的方法是自己解析字符串。注意:Date
应该用于存储微秒时间,但您也可以使用 long
(它也可用于毫秒或纳秒)。
private static final String YEARS_TO_MINUTES = "yyyy-MM-dd HH:mm";
private static final SimpleDateFormat YEARS_TO_MINUTES_SDF = new SimpleDateFormat(YEARS_TO_MINUTES);
public static long parseMicroSeconds(String text) throws ParseException {
long timeMS;
synchronized (YEARS_TO_MINUTES_SDF) {
timeMS = YEARS_TO_MINUTES_SDF.parse(text.substring(0, YEARS_TO_MINUTES.length())).getTime();
}
long microSecs = 0;
if (text.length() > YEARS_TO_MINUTES.length() + 1) {
double secs = Double.parseDouble(text.substring(YEARS_TO_MINUTES.length() + 1));
microSecs = (long) (secs * 1e6 + 0.5);
}
return timeMS * 1000 + microSecs;
}
public static String formatMicroSeconds(long timeMicroSeconds) {
String dateTime;
synchronized (YEARS_TO_MINUTES_SDF) {
dateTime = YEARS_TO_MINUTES_SDF.format(new Date(timeMicroSeconds / 1000));
}
long secs = timeMicroSeconds % 60000000;
return dateTime + String.format(":%09.6f", secs / 1e6);
}
public static void main(String... args) throws ParseException {
String dateTime = "2011-01-17 19:27:59.999650";
long timeUS = parseMicroSeconds(dateTime);
for (int i = 0; i < 5; i++)
System.out.println(formatMicroSeconds(timeUS += 175));
}
打印
2011-01-17 19:27:59.999825
2011-01-17 19:28:00.000000
2011-01-17 19:28:00.000175
2011-01-17 19:28:00.000350
2011-01-17 19:28:00.000525
您可以尽力做到以下最佳实践:
SimpleDateFormat sDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
:SS
。import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class MyClass
{
public static void main(String args[]) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss:SSSSS");
for(int i=0; i<=5;i++) {
System.out.println("Class 1 : " + ZonedDateTime.now().format(formatter));
}
}
}
示例输出:
Class 1 : 19:25:19:77336
Class 1 : 19:25:19:77483
Class 1 : 19:25:19:77487
Class 1 : 19:25:19:77490
Class 1 : 19:25:19:77493
Class 1 : 19:25:19:77496
查看 SimpleDateFormat 的 Java-doc,它告诉我们:
毫秒:S
微秒不可用。
yyyy-MM-dd HH:mm:ss:SSS
。欲了解更多信息,请参考自定义格式。这个示例获取毫秒。微秒不可用。
Date someDate = sDate.parse(dateString);
Calendar c = Calendar.setTime(someDate);
int millisecond = c.get(Calendar.MILLISECOND);
SimpoleDateFormat
。它是一个臭名昭著的麻烦制造者类。请使用来自java.time,现代Java日期和时间API的类。 - Ole V.V.