Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Date() object gives the same value

Tags:

java

date

I have some code that utilizes the Date object as the name of a file in order to have distinct file names every time but the strange thing is that a new Date object gives off the same toString() for each loop iteration. I mean, the following:

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

Log.d("Date", d.toString());

is executed in loops.

Side note: Since this is related to Java API, I haven't tagged the question as that of Android but the OS that executes this code is Android.

AFAIK, new Date() uses System.currentTimeMilis() as the init value, what might be reason for this unusual behavior?

like image 832
Manish Kumar Sharma Avatar asked Nov 21 '17 07:11

Manish Kumar Sharma


People also ask

What does new Date () return?

"The expression new Date() returns the current time in internal format, as an object containing the number of milliseconds elapsed since the start of 1970 in UTC.

What is the difference between new Date () and Date?

Date() returns an implementation dependent string representing the current date and time. new Date() returns a Date object that represents the current date and time. ;-) Yeah, I know.

Does new Date () Return current Date?

Use new Date() to generate a new Date object containing the current date and time. This will give you today's date in the format of mm/dd/yyyy.

What is new in new Date () in JavaScript?

new Date() returns the date based on the input parameter and Date() returns todays date on the browser. Show activity on this post. Thus , if you called it like method , it re-call the constructor to return the current date&time . Interesting, but note that typeof Date() === 'string' , not 'object' .


1 Answers

You format your time as yyyyMMdd_HHmmss, but the run of a loop needs just milliseconds, so use yyyyMMdd_HHmmssSSS to get a more acurate time.

As Jon Skeet mentions in his comment, the run of a loop could even take less than a millisecond (depending on the tasks you perform), so you could run into issues with this solution as well!

like image 94
Sergej Avatar answered Sep 28 '22 04:09

Sergej