下面的代码给出了当前时间。但是它并没有告诉我们毫秒。

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可以很好地工作。这里最低的时间单位是秒,但我怎么也能得到毫秒呢?


当前回答

Ans:

DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
ZonedDateTime start = Instant.now().atZone(ZoneId.systemDefault());
String startTimestamp = start.format(dateFormatter);

其他回答

我会用这样的方法:

String.format("%tF %<tT.%<tL", dateTime);

变量dateTime可以是任何日期和/或时间值,参见JavaDoc中的Formatter。

使用此命令获取指定格式的当前时间:

 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 System.out.print(dateFormat.format(System.currentTimeMillis()));  }

为了补充上述答案,这里有一个小的工作示例程序,打印当前时间和日期,包括毫秒。

import java.text.SimpleDateFormat;
import java.util.Date;

public class test {
    public static void main(String argv[]){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        Date now = new Date();
        String strDate = sdf.format(now);
        System.out.println(strDate);
    }
}

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的信息。

你只需要在日期格式字符串中添加毫秒字段:

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

SimpleDateFormat的API文档详细描述了格式字符串。