Stewie Griffin
Stewie Griffin

Reputation: 9327

Javascript increment number..missing logic

need some logics or algorithm here:

I want to use javascript to implement a simple counter, which adds rand() int every day (ignoring page loads) and stores that number without using any database... It doesn't have so start from 0, but it has to be increasing everyday. Example: 2050. Next day: 2053..and so on.

I am thinking to use javascript date function, as year is increasing and month numbers are increasing (each year), but days set to 1 each month.. So any ideas what kind of algorithm or javascript function I could use to implement this?

It would be perfect to have rand() function, which increments only, but everyday, not every page load.. Probably it's silly question, but it's Saturday and my brain doesnt function anymore.. :) Thank you so much!

Update: getTime() kinda does the thing, but it gives me smth like 8176870165464, there last digits are miliseconds, so they are changing too often..I need to increment +1 or +3 ( or relatively small int) every day..and the final counter to be 4 digits, smth like 2040, not 345346345355

Upvotes: 0

Views: 571

Answers (4)

markijbema
markijbema

Reputation: 4055

Does it need to be random? Or just increasing? The following increases by 1 each day:

date = Math.floor(Date().getTime() / (24*60*60*1000));

edit: replaced mod above with a div (or at least, a hack to get a div, since JS doesn't support div)

If it needs to be random (in the sense of unpredictable) you need to do something like this:

nr = nr * 100 + yourrandomfunction(nr,100)

Where yourrandomfunction returns a random number given seed 'nr' and max '100'. But unfortunately, you need to build this yourself:

Seeding the random number generator in Javascript

Upvotes: 0

SoapBox
SoapBox

Reputation: 20609

If you just need a number that goes up every 24 hours, use the current time. javascript's Date.getTime() returns the number of milliseconds since 1970. This will always be going up, if you only want it to change every 24 hours, just divide the number it returns by 24*60*60*1000. (Note that in the case of leap seconds and daylight savings time, there can be more or less than 24 hours in a day.)

Upvotes: 1

Cosmin
Cosmin

Reputation: 2385

You can use the current date. To make it increasing, just compute the number of days since a given day in the past.

Upvotes: 2

Marc B
Marc B

Reputation: 360812

Does the number have to be globally unique? Unique per-user? Can it repeat for a user?

Either way, you'd have to store it in a cookie, or store it somewhere on your server. And if it's on your server, then there's no point in having Javascript generate it, just have your server-side language of choice do it.

Upvotes: 0

Related Questions