Is there a millisecond letter since 1970 in SimpleDateFormat?

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

+5
source share
1 answer

SimpleDateFormat does not have a character (letter) to insert milliseconds from the beginning of the era, starting January 1, 1970, 00:00:00 UTC.

Reason: to be honest, only inserting milliseconds from the beginning of an era is just inserting the long value returned by Date.getTime() , the value of the moment when the time is displayed ( Date ), which is not very useful when your goal is to create a readable formatted date string / time. Therefore, I do not see that the symbol was justified. You can easily add this number or include its value, as with any other prime number.

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

String.format() uses a string that also supports date / time conversions, which are very similar to the SimpleDateFormat pattern.

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

You also have the symbol: 'Q' : milliseconds since the beginning of the era, starting January 1, 1970, 00:00:00 UTC.

What's even better, String.format() is flexible enough to accept long and Date values ​​as input to date / time conversions.

Using:

 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)" 
+6
source

Source: https://habr.com/ru/post/1201872/


All Articles