Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a letter for the milliseconds since 1970 in SimpleDateFormat?

Tags:

java

timestamp

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.

like image 929
principal-ideal-domain Avatar asked Sep 05 '14 08:09

principal-ideal-domain


1 Answers

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)"
like image 108
icza Avatar answered Sep 22 '22 06:09

icza