如何在 Java 中以 YYYY-MM-DD HH:MI:Sec.Millisecond 格式获取当前时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1459656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:30:33  来源:igfitidea点击:

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

javadate

提问by Sunil Kumar Sahoo

The code below gives me the current time. But it does not tell anything about milliseconds.

下面的代码给了我当前的时间。但它没有说明任何关于毫秒的信息。

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;
}

I get date in the format 2009-09-22 16:47:08(YYYY-MM-DD HH:MI:Sec).

我以2009-09-22 16:47:08(YYYY-MM-DD HH:MI:Sec)格式获取日期。

But I want to retrieve the current time in the format 2009-09-22 16:47:08.128((YYYY-MM-DD HH:MI:Sec.Ms)- where 128 tells the millisecond.

但我想以格式2009-09-22 16:47:08.128((YYYY-MM-DD HH:MI:Sec.Ms)-检索当前时间,其中 128 表示毫秒。

SimpleTextFormatwill work fine. Here the lowest unit of time is second, but how do I get millisecond as well?

SimpleTextFormat会正常工作。这里最低的时间单位是秒,但我如何获得毫秒?

采纳答案by JayJay

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

回答by Michael Borgwardt

You only have to add the millisecond field in your date format string:

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

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

The API doc of SimpleDateFormatdescribes the format string in detail.

SimpleDateFormatAPI 文档详细描述了格式字符串。

回答by duggu

try this:-

尝试这个:-

http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = new Date();
System.out.println(dateFormat.format(date));

or

或者

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));

回答by Basil Bourque

tl;dr

tl;博士

Instant.now()
       .toString()

2016-05-06T23:24:25.694Z

2016-05-06T23:24:25.694Z

ZonedDateTime
.now
( 
    ZoneId.of( "America/Montreal" ) 
)
.format(  DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " )

2016-05-06 19:24:25.694

2016-05-06 19:24:25.694

java.time

时间

In Java 8 and later, we have the java.timeframework built into Java 8 and later. These new classes supplant the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Timeframework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extraproject. See the Tutorial.

在 Java 8 及更高版本中,我们在 Java 8 及更高版本中内置了java.time框架。这些新类取代了麻烦的旧 java.util.Date/.Calendar 类。新类的灵感来自非常成功的Joda-Time框架,作为其继承者,概念相似但重新构建。由JSR 310定义。由ThreeTen-Extra项目扩展。请参阅教程

Be aware that java.time is capable of nanosecondresolution (9 decimal places in fraction of second), versus the millisecondresolution (3 decimal places) of both java.util.Date & Joda-Time. So when formatting to display only 3 decimal places, you could be hiding data.

请注意,java.time 具有纳秒分辨率(以秒为单位的9 个小数位),而java.util.Date 和 Joda-Time的毫秒分辨率(3 个小数位)则不同。因此,当格式化为仅显示 3 个小数位时,您可能隐藏了数据。

If you want to eliminate any microseconds or nanoseconds from your data, truncate.

如果要从数据中消除任何微秒或纳秒,请截断。

Instant instant2 = instant.truncatedTo( ChronoUnit.MILLIS ) ;

The java.time classes use ISO 8601format by default when parsing/generating strings. A Zat the end is short for Zulu, and means UTC.

java.time 类在解析/生成字符串时默认使用ISO 8601格式。Z末尾的A是 , 的缩写Zulu,表示UTC

An Instantrepresents a moment on the timeline in UTC with resolution of up to nanoseconds. Capturing the current momentin Java 8 is limited to milliseconds, with a new implementation in Java 9 capturing up to nanoseconds depending on your computer's hardware clock's abilities.

AnInstant代表 UTC 时间轴上的一个时刻,分辨率高达纳秒。在 Java 8 中捕获当前时刻仅限于毫秒,而 Java 9 中的新实现可以根据计算机硬件时钟的能力捕获最多纳秒。

Instant instant = Instant.now (); // Current date-time in UTC.
String output = instant.toString ();

2016-05-06T23:24:25.694Z

2016-05-06T23:24:25.694Z

Replace the Tin the middle with a space, and the Zwith nothing, to get your desired output.

T空格替换中间的 ,而Z什么也没有,以获得您想要的输出。

String output = instant.toString ().replace ( "T" , " " ).replace( "Z" , "" ; // Replace 'T', delete 'Z'. I recommend leaving the `Z` or any other such [offset-from-UTC][7] or [time zone][7] indicator to make the meaning clear, but your choice of course.

2016-05-06 23:24:25.694

2016-05-06 23:24:25.694

As you don't care about including the offset or time zone, make a "local" date-time unrelated to any particular locality.

由于您不关心包括偏移量或时区,因此请制作与任何特定地点无关的“本地”日期时间。

String output = LocalDateTime.now ( ).toString ().replace ( "T", " " );

Joda-Time

乔达时间

The highly successful Joda-Time library was the inspiration for the java.time framework. Advisable to migrate to java.time when convenient.

非常成功的 Joda-Time 库是 java.time 框架的灵感来源。建议在方便时迁移到 java.time。

The ISO 8601format includes milliseconds, and is the default for the Joda-Time2.4 library.

ISO 8601的格式包含毫秒,对于默认的乔达时间2.4库。

System.out.println( "Now: " + new DateTime ( DateTimeZone.UTC ) );

When run…

运行时…

Now: 2013-11-26T20:25:12.014Z

Also, you can ask for the milliseconds fraction-of-a-second as a number, if needed:

此外,如果需要,您可以要求将毫秒分数作为一个数字:

int millisOfSecond = myDateTime.getMillisOfSecond ();

回答by Joram

A Java one liner

一个 Java one liner

public String getCurrentTimeStamp() {
    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
}

in JDK8 style

JDK8 风格

public String getCurrentLocalDateTimeStamp() {
    return LocalDateTime.now()
       .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
}

回答by ttb

To complement the above answers, here is a small working example of a program that prints the current time and date, including milliseconds.

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

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);
    }
}

回答by Android Dev

You can simply get it in the format you want.

您可以简单地以您想要的格式获取它。

String date = String.valueOf(android.text.format.DateFormat.format("dd-MM-yyyy", new java.util.Date()));

回答by Usagi Miyamoto

I would use something like this:

我会使用这样的东西:

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

Variable dateTimecould be any date and/or time value, see JavaDoc for Formatter.

变量dateTime可以是任何日期和/或时间值,请参阅JavaDoc forFormatter.

回答by prime

The easiest way was to (prior to Java 8) use,

最简单的方法是(在 Java 8 之前)使用,

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

But SimpleDateFormatis not thread-safe. Neither java.util.Date. This will lead to leading to potential concurrency issues for users. And there are many problems in those existing designs. To overcome these now in Java 8 we have a separate package called java.time. This Java SE 8 Date and Timedocument has a good overview about it.

SimpleDateFormat不是线程安全的。既不是java.util.Date。这将导致用户面临潜在的并发问题。而那些现有的设计存在很多问题。为了在 Java 8 中克服这些问题,我们有一个名为java.time的单独包。这个Java SE 8 日期和时间文档有一个很好的概述。

So in Java 8 something like below will do the trick (to format the current date/time),

所以在 Java 8 中,像下面这样的东西会起作用(格式化当前日期/时间),

LocalDateTime.now()
   .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));

And one thing to note is it was developed with the help of the popular third party library joda-time,

需要注意的一件事是它是在流行的第三方库joda-time的帮助下开发的,

The project has been led jointly by the author of Joda-Time (Stephen Colebourne) and Oracle, under JSR 310, and will appear in the new Java SE 8 package java.time.

该项目由 Joda-Time 的作者(Stephen Colebourne)和 Oracle 联合领导,在 JSR 310 下,并将出现在新的 Java SE 8 包 java.time 中。

But now the joda-timeis becoming deprecated and asked the users to migrate to new java.time.

但是现在已经joda-time过时了,并要求用户迁移到新的java.time.

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project

请注意,从 Java SE 8 开始,要求用户迁移到 java.time (JSR-310) - JDK 的核心部分,它取代了这个项目

Anyway having said that,

话虽这么说,

If you have a Calendarinstance you can use below to convert it to the new java.time,

如果您有一个Calendar实例,您可以使用下面的方法将其转换为新的java.time

    Calendar calendar = Calendar.getInstance();
    long longValue = calendar.getTimeInMillis();         

    LocalDateTime date =
            LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
    String formattedString = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));

    System.out.println(date.toString()); // 2018-03-06T15:56:53.634
    System.out.println(formattedString); // 2018-03-06 15:56:53.634

If you had a Date object,

如果你有一个 Date 对象,

    Date date = new Date();
    long longValue2 = date.getTime();

    LocalDateTime dateTime =
            LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue2), ZoneId.systemDefault());
    String formattedString = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));

    System.out.println(dateTime.toString()); // 2018-03-06T15:59:30.278
    System.out.println(formattedString);     // 2018-03-06 15:59:30.278

If you just had the epoch milliseconds,

如果你只有纪元毫秒,

LocalDateTime date =
        LocalDateTime.ofInstant(Instant.ofEpochMilli(epochLongValue), ZoneId.systemDefault());

回答by ejaenv

The doc in Java 8 names it fraction-of-second, while in Java 6 was named millisecond. This brought me to confusion

Java 8 中的文档将其命名为小数秒,而在 Java 6 中命名为毫秒。这让我感到困惑