【问题标题】:How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?如何在 Java 中以 YYYY-MM-DD HH:MI:Sec.Millisecond 格式获取当前时间?
【发布时间】:2010-11-30 09:17:33
【问题描述】:

下面的代码给了我当前时间。但它并没有说明毫秒。

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.MS2009-09-22 16:47:08.128,其中128 是毫秒)格式检索当前时间。

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

【问题讨论】:

标签: java date


【解决方案1】:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

【讨论】:

  • 出于好奇,使用 SimpleDateFormat 带来了什么好处: dateTime.ToString("yyyy-MM-dd HH:mm:ss.SSS") ?
  • @NickG 这个toString(String format) 方法在哪里? java.util.Date 似乎没有。您指的是 Joda Time API 吗?但一个可能的好处是重用相同的格式化程序对象。另一个是您不必添加 API - Date 类是标准 Java 库类。
  • 在 Java 8 中,您可以将DateTimeFormatter 用于相同目的。
  • SimpleDateFormat 不是线程安全的,但较新的 DateTimeFormatter 是线程安全的。
  • 使用 Java 8 日期时间 API:LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))
【解决方案2】:

Java 单线器

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

JDK8 风格

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

【讨论】:

【解决方案3】:

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

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

API doc of SimpleDateFormat 详细描述了格式字符串。

【讨论】:

    【解决方案4】:

    试试这个:-

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

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

    【讨论】:

      【解决方案5】:

      tl;博士

      Instant.now()
             .toString()
      

      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

      java.time

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

      请注意,java.time 具有 nanosecond 分辨率(9 位小数,秒的分数),而 java.util.Date 和 Joda-Time 的 millisecond 分辨率(3 位小数)。因此,当格式化为仅显示 3 位小数时,您可能会隐藏数据。

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

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

      java.time 类在解析/生成字符串时默认使用ISO 8601 格式。末尾的ZZulu 的缩写,意思是UTC

      Instant 代表 UTC 时间线上的一个时刻,分辨率高达 nanoseconds。 Java 8 中的 Capturing the current moment 仅限于 milliseconds,Java 9 中的新实现可以捕获多达纳秒,具体取决于您计算机的硬件时钟能力。

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

      2016-05-06T23:24:25.694Z

      将中间的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

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

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

      乔达时间

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

      ISO 8601 格式包括毫秒,是 Joda-Time 2.4 库的默认值。

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

      运行时……

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

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

      int millisOfSecond = myDateTime.getMillisOfSecond ();
      

      【讨论】:

        【解决方案6】:

        我会使用这样的东西:

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

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

        【讨论】:

          【解决方案7】:

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

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

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

          所以在 Java 8 中,类似下面的东西可以解决问题(格式化当前日期/时间),

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

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

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

          但现在joda-time 已被弃用,并要求用户迁移到新的java.time

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

          话虽如此,

          如果您有一个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
          

          如果你有一个 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
          

          如果你只有纪元毫秒,

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

          【讨论】:

          • 最低 API 级别为 26
          【解决方案8】:

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

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

          【讨论】:

            【解决方案9】:

            我这里有一个简单的例子,用毫秒显示日期和时间......

            import java.time.LocalDateTime;
            import java.time.format.DateTimeFormatter;
            
            public class MyClass{
            
                public static void main(String[]args){
                    LocalDateTime myObj = LocalDateTime.now();
                    DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
                    String forDate = myObj.format(myFormat);
                    System.out.println("The Date and Time are: " + forDate);
                }
            }
            

            【讨论】:

            【解决方案10】:

            使用它以指定格式获取您的当前时间

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

            【讨论】:

            • 仅供参考,非常麻烦的旧日期时间类,如 java.util.Datejava.util.Calendarjava.text.SimpleDateFormat 现在是 legacy,被 Java 8 中内置的 java.time 类所取代,之后。见Tutorial by Oracle
            • 其实我在 Android App 中使用了这个解决方案,但是要在 Android 中使用 Java.time 类,我们需要将 API 设置为至少 27。无论如何感谢分享信息。
            • 几乎所有的 java.time 功能都通过几乎相同的 API 向后移植到 ThreeTen-Backport 项目中的 Java 6 和 7 . ThreeTenABP 项目中进一步适配 Android
            【解决方案11】:

            我没有看到对此的参考:

            SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            

            上述格式也很有用。

            http://www.java2s.com/Tutorials/Java/Date/Date_Format/Format_date_in_yyyyMMddHHmmssSSS_format_in_Java.htm

            【讨论】:

              【解决方案12】:

              回答:

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

              【讨论】:

                【解决方案13】:

                Java 8 中的文档将其命名为 fraction-of-second,而在 Java 6 中则命名为 millisecond。这让我很困惑

                【讨论】:

                  【解决方案14】:

                  java.text(Java 8 之前的版本)

                  public static ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
                      protected DateFormat initialValue() {
                          return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
                      };
                  };
                  
                  ...
                  dateFormat.get().format(new Date());
                  

                  java.time

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

                  【讨论】:

                    【解决方案15】:

                    你可以简单地得到你想要的格式。

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

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 2011-12-06
                      • 2014-07-09
                      • 2013-10-04
                      • 1970-01-01
                      • 2011-06-29
                      • 1970-01-01
                      • 2018-04-07
                      • 1970-01-01
                      相关资源
                      最近更新 更多