802

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 have a date in the format YYYY-MM-DD HH:MM:SS (2009-09-22 16:47:08).

But I want to retrieve the current time in the format YYYY-MM-DD HH:MM:SS.MS (2009-09-22 16:47:08.128, where 128 are the milliseconds).

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

Neuron
  • 5,141
  • 5
  • 38
  • 59
Sunil Kumar Sahoo
  • 53,011
  • 55
  • 178
  • 243
  • 37
    When all else fails, read the [documentation](http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns). – Hot Licks Jun 03 '14 at 11:45
  • 6
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html), and `java.text.SimpleTextFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque May 31 '17 at 00:22

16 Answers16

1211
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
JayJay
  • 12,275
  • 1
  • 16
  • 4
  • 1
    Out of curiosity, what benefit does using SimpleDateFormat bring over just: dateTime.ToString("yyyy-MM-dd HH:mm:ss.SSS") ? – NickG May 08 '13 at 09:43
  • 10
    @NickG Where is this `toString(String format)` method? The `java.util.Date` doesn't seem to have it. Are you referring to the Joda Time API? But one possible benefit is reuse of the same formatter object. Another is you don't have to add an API - Date class is a standard Java library class. – ADTC Jul 17 '13 at 02:21
  • 25
    In Java 8 you can use [DateTimeFormatter](http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html) for the same purpose. – Vitalii Fedorenko Apr 20 '14 at 17:52
  • 7
    SimpleDateFormat is not thread safe, but the newer DateTimeFormatter is thread safe. – devdanke May 25 '17 at 06:22
  • 33
    Using Java 8 datetime API: `LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))` – rsinha Dec 14 '17 at 19:41
  • I found this one for Date `SimpleDateFormat.getDateInstance(DateFormat.SHORT)` but seems there is no template for Time and Date at the same time – user25 Aug 23 '18 at 10:59
  • FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Nov 16 '18 at 06:37
  • VERY Important to note that it is NOT the same behavior as the regular Oracle Java library. Oracle Java will show 3 digits for ".S", as it stands specifically for milliseconds. Whereas Android ".S" stands for fractions of seconds. With Oracle Java you can only use one "S" (and always shows 3 digits), but in Android you can use any number of "S" characters you require, one digit shown per "S". – Dave Hubbard Dec 28 '19 at 18:19
253

A Java one liner

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

in JDK8 style

public String getCurrentLocalDateTimeStamp() {
    return LocalDateTime.now()
       .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
}
catch23
  • 17,519
  • 42
  • 144
  • 217
Joram
  • 3,166
  • 1
  • 22
  • 29
119

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 SimpleDateFormat describes the format string in detail.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
49

try this:-

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()));
duggu
  • 37,851
  • 12
  • 116
  • 113
44

tl;dr

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

In Java 8 and later, we have the java.time framework 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-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.

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

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 8601 format by default when parsing/generating strings. A Z at the end is short for Zulu, and means UTC.

An Instant represents a moment on the timeline in UTC with resolution of up to nanoseconds. Capturing the current moment in 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.

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

2016-05-06T23:24:25.694Z

Replace the T in the middle with a space, and the Z with nothing, to get your desired output.

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

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.

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

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 ();
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
13

I would use something like this:

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

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

Usagi Miyamoto
  • 6,196
  • 1
  • 19
  • 33
12

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

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

But SimpleDateFormat is 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 Time document has a good overview about it.

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

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,

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.

But now the joda-time is becoming deprecated and asked the users to migrate to new 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

Anyway having said that,

If you have a Calendar instance you can use below to convert it to the new 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 = 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());
prime
  • 14,464
  • 14
  • 99
  • 131
9

I have a simple example here to display date and time with Millisecond......

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);
    }
}
slartidan
  • 20,403
  • 15
  • 83
  • 131
  • Looks good, but does it add insight over, say, [rsinha's 5-year-old comment](https://stackoverflow.com/questions/1459656/how-to-get-the-current-time-in-yyyy-mm-dd-hhmisec-millisecond-format-in-java#comment82604221_1459683)? – greybeard Dec 08 '19 at 18:25
4

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

ttb
  • 229
  • 3
  • 12
3

Use this to get your current time in specified format :

 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 System.out.print(dateFormat.format(System.currentTimeMillis()));  }
Abhishek Sengupta
  • 2,938
  • 1
  • 28
  • 35
  • FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Nov 16 '18 at 06:37
  • Actually I was using this solution for Android App , but to use Java.time class in Android we need to have API set to at least 27. Anyway thanks for sharing the information. – Abhishek Sengupta Nov 16 '18 at 10:24
  • Nearly all of the *java.time* functionality is back-ported to Java 6 & 7 in the *ThreeTen-Backport* project with virtually the same API. Further adapted to Android <26 in the *ThreeTenABP* project. So there is no reason to ever touch those bloody awful old date-time classes again. – Basil Bourque Nov 16 '18 at 16:49
2

java.time

The question and the accepted answer use java.util.Date and SimpleDateFormat which was the correct thing to do in 2009. In Mar 2014, the java.util date-time API and their formatting API, SimpleDateFormat were supplanted by the modern date-time API. Since then, it is highly recommended to stop using the legacy date-time API.

Solution using java.time, the modern date-time API:

LocalDateTime.now(ZoneId.systemDefault())
             .format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS"))

Some important points about this solution:

  1. Replace ZoneId.systemDefault() with the applicable ZoneId e.g. ZoneId.of("America/New_York").
  2. If the current date-time is required in the system's default timezone (ZoneId), you do not need to use LocalDateTime#now(ZoneId zone); instead, you can use LocalDateTime#now().
  3. You can use y instead of u here but I prefer u to y.

Demo:

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

Output from a sample run in my system's timezone, Europe/London:

2023-01-02 09:53:14.353

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

I don't see a reference to this:

SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmssSSS");

above format is also useful.

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

Zoe
  • 27,060
  • 21
  • 118
  • 148
Smart Coder
  • 1,435
  • 19
  • 19
1

Ans:

DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
ZonedDateTime start = Instant.now().atZone(ZoneId.systemDefault());
String startTimestamp = start.format(dateFormatter);
Julian
  • 33,915
  • 22
  • 119
  • 174
1

java.text (prior to 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());
Mike
  • 20,010
  • 25
  • 97
  • 140
0

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

ejaenv
  • 2,117
  • 1
  • 23
  • 28
-1

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()));
Android Dev
  • 1,496
  • 1
  • 13
  • 25