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?
"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.
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.
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.
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' .
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With