5

Is there a letter for the milliseconds since 1970 in SimpleDateFormat? I know about the getTime() method but I want to define a date and time pattern containing the milliseconds.

principal-ideal-domain
  • 3,998
  • 8
  • 36
  • 73
  • 2
    Can you read the page you linked? If there is, it will be listed there. – icza Sep 05 '14 at 08:25
  • http://stackoverflow.com/questions/4142313/java-convert-milliseconds-to-time-format?rq=1 – Black Sheep Sep 05 '14 at 08:26
  • 1
    According to [the docs](http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html) it doesn't look like there is one – Clive Sep 05 '14 at 08:33
  • I can read and I didn't find it. So with the current question I wanted to make sure that there really isn't such a letter. Probably there is a reason for it. Maybe someone can tell me. – principal-ideal-domain Sep 05 '14 at 09:03

1 Answers1

8

SimpleDateFormat does not have a symbol (letter) for inserting the milliseconds since the beginning of the epoch starting at 1 January 1970 00:00:00 UTC.

Reason: Frankly just inserting the milliseconds since the beginning of the epoch is just inserting the long value returned by Date.getTime(), the value how an instant in time (Date) is represeneted, which is not very useful when your goal is to create a human-readable, formatted date/time string. So I don't see having a symbol for this being justified. You can append this number easily or have its value included as you would with any other simple number.

However, there is an alternative: String.format()

String.format() uses a format string which also supports Date/Time conversions which is very similar to the pattern of SimpleDateFormat.

For example there is a symbol 'H' for the Hour of the day (24-hour clock), 'm' for Month (two digits) etc., so in most cases String.format() can be used instead of SimpleDateFormat.

What you're interested in is also has a symbol: 'Q': Milliseconds since the beginning of the epoch starting at 1 January 1970 00:00:00 UTC.

What's even better, String.format() is flexible enough to accept both long values and Dates as the input parameter for Date/Time conversions.

Usage:

System.out.println(String.format("%tQ", System.currentTimeMillis()));
System.out.println(String.format("%tQ", new Date()));

// Or simply:
System.out.printf("%tQ\n", System.currentTimeMillis());
System.out.printf("%tQ\n", new Date());

// Full date+time+ millis since epoc:
Date d = new Date();
System.out.printf("%tF %tT (%tQ)", d, d, d);
// Or passing the date only once:
System.out.printf("%1$tF %1$tT (%1$tQ)", d);

// Output: "2014-09-05 11:15:58 (1409908558117)"
icza
  • 389,944
  • 63
  • 907
  • 827