2

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?

1
  • 2
    new Date().getTime() returns Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch). Commented Mar 2, 2014 at 5:56

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

1

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

A 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.
You're right, it's the wrong term, I'm updating the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.