The new Date () object gives the same value

I have code that uses a Date object as a file name to have different file names each time, but it is strange that a new Date object allocates the same toString() for each iteration of the loop. I mean the following:

 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); String fileName = sdf.format((d = new Date())) + ".jpg"; Log.d("Date", d.toString()); 

performed in cycles.

Side note: Since this is related to the Java API, I did not mark this question as an Android issue, but the OS running this code is Android.

AFAIK, new Date() uses System.currentTimeMilis() as the value of init, what could be causing this unusual behavior?

+5
source share
3 answers

You will format your time as yyyyMMdd_HHmmss , but it only takes a millisecond to loop, so use yyyyMMdd_HHmmssSSS to get a more accurate time.

As John Skeet mentions in his comment, it can even take less than a millisecond to start a cycle (depending on the tasks being performed), so you may run into problems with this solution!

+5
source

java.time

The modern approach uses java.time classes.

The Instant class represents a point on the timeline with a resolution of nanoseconds. The Instant.now command captures the current moment in milliseconds in Java 8 and in microseconds in Java 9 (or, possibly, more subtle).

Replace colon characters for MacOS compatibility.

 String filename = Instant.now().toString().replace( ":" , "-" ) + ".jpeg" ; 

Please note that even with milliseconds or microseconds, you may run into conflicts when running short code on fast kernels. I suggest using a UUID to eliminate this risk.

Uuid

If you just want unique file names without requiring a current moment in the name, use the UUID rather than the -time date.

The UUID class can generate some versions, such as version 4 (mostly random):

 String filename = UUID.randomUUID() + ".jpeg" ; 
+3
source

Java in a loop is faster than one second, it will remain the same to make sure that it is always unique especially in a multi-line function .

Use something like this

 SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss:SSSSSSS"); 

Some tips so you don't run into a big debugging problem

  printDate("dd.MM.yyyy HH:mm:ss.SSS");//02.05.2010 21:45:58.073 printDate("dd.MM.yyyy HH:mm:ss.SSSSSS");//02.05.2010 21:45:58.000073 printDate("dd.MM.yyyy HH:mm:ss.SSS'000'");//02.05.2010 21:45:58.073000 printDate("dd.MM.yyyy HH:mm:ss.'000000'");//02.05.2010 21:45:58.000000 tryToParseDate("dd.MM.yyyy HH:mm:ss.SSS");//good tryToParseDate("dd.MM.yyyy HH:mm:ss.SSSSSS");//good tryToParseDate("dd.MM.yyyy HH:mm:ss.SSS'000'");//bad tryToParseDate("dd.MM.yyyy HH:mm:ss.'000000'");//good 

Reference:

@slartidan Answer

Nanosecond String-Date Conversion

As a recommendation, when I came across this situation:

1) If you call from S3 AWS

it should be called unique when starting the file name, it will do hashing and searching pretty quickly. as one of AWS S3 best practices for optimization.

  public static String genarateFileName(String name) { StringBuilder sb = new StringBuilder(name); sb.insert(0, IdUtil.getUniqueUuid());in short to increase performance of S3 put and get etc..) if (sb.lastIndexOf(".") != -1) { sb.insert(sb.lastIndexOf("."), "_" + System.nanoTime()); } else { sb.append("_").append(System.nanoTime()); } return sb.toString(); } 

2) To create random nano

  public static String getUniqueUuid() { int rand = (int) (Math.random() * 100); return Integer.toHexString(rand) + Long.toHexString(java.lang.System.nanoTime()); } 

3) I use as random nano with random string check below, generate random string of some length

  /** * Generate a random uuid of the specified length. Example: uuid(15) returns * "VcydxgltxrVZSTV" * * @param len the desired number of characters * @return */ public static String uuid(int len) { return uuid(len, CHARS.length); } /** * Generate a random uuid of the specified length, and radix. Examples: <ul> * <li>uuid(8, 2) returns "01001010" (8 character ID, base=2) <li>uuid(8, * 10) returns "47473046" (8 character ID, base=10) <li>uuid(8, 16) returns * "098F4D35" (8 character ID, base=16) </ul> * * @param len the desired number of characters * @param radix the number of allowable values for each character (must be * <= 62) * @return */ public static String uuid(int len, int radix) { if (radix > CHARS.length) { throw new IllegalArgumentException(); } char[] uuid = new char[len]; // Compact form for (int i = 0; i < len; i++) { uuid[i] = CHARS[(int) (Math.random() * radix)]; } return new String(uuid); } 
0
source

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


All Articles