I used to use the code to create a string of numbers for my filenames to avoid duplicates. What it does is that it will send me a string of numbers of the exact current time that is very accurate (like 1/1000000000 of a second). I don't remember how I did it anymore since I kept just copy and paste my old codes. Do anyone know how to do that?
3 Answers
There is a good reference at MDN about the Javascript Date constructor/object. But basically, in older environments, do.
new Date().getTime()
In newer environments you can do
Date.now()
Both return an Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch).
You can also do
new Date().valueOf()
but it could be less reliable than those above.
Comments
The current time in javascript is only provided to a number of milliseconds. If generating multiple filenames at once, you may get the same current time when requested multiple times during the same operation. So, if you want a totally unique number (with even more uniqueness than the current milliseconds so you can generate a number of these in a tight loop), you can combine the time with a randomly generated value like this:
function makeUnique(base) {
var now = new Date().getTime();
var random = Math.floor(Math.random() * 100000);
return base + now + random;
}
makeUnique("test");
Working demo: http://jsfiddle.net/jfriend00/dpZLC/
If you want the filename to always be the same number of digits, you can zero pad the random number like this:
function makeUnique(base) {
var now = new Date().getTime();
var random = Math.floor(Math.random() * 100000);
// zero pad random
random = "" + random;
while (random.length < 5) {
random = "0" + random;
}
return base + now + random;
}
Comments
You can create retrieve the number of milliseconds that have elapsed since the epoch by using the getTime method of the Date object.
var now = new Date(); console.log(now.getTime());
2 Comments
Unix timestamp is different.the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970. You would have to divide the javascript timestamp by 1000 to get seconds.
new Date().getTime()returnsInteger value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch).