Warface
Warface

Reputation: 5119

Add 24 hours to getTime() for each 5000 characters

I would to make a javascript loop that would return me the date depending on how much characters are in a document.

var d = new Date.getTime();
var s = 9349859; //Random number of characters

if(s < 5000){
   d = "Same day";
}else{
   //Do the loop I'm searching
   ....

But if I want to make a loop that every 5000 characters that it will add 24 hours to the getTime() var. How ?

Upvotes: 0

Views: 166

Answers (4)

Jamiec
Jamiec

Reputation: 136154

You dont need any loop for this. Simply divide number of characters by 5000 to get the number of days to add. You might want to floor (round down) or ceil (round up). My example rounds up - therefore adding a day for every 5000 characters or part thereof:

var d = new Date();
var s = 9349859; //Random number of characters

var numDays = Math.ceil(s/5000);

var newDate = new Date()
newDate.setDate(d.getDate() + numDays);

Live example: http://jsfiddle.net/SJV26/

Upvotes: 0

Max Langerak
Max Langerak

Reputation: 1207

What you simply could do is something like this:

Date.prototype.addHours= function(h){
    this.setHours(this.getHours()+h);
    return this;
}

var d = new Date.getTime();
var s = 9349859; //Random number of characters
var h = 0;

if(s < 5000){
   d = "Same day";
}else{
   while(s >= 5000) {
      h++;
      s -= 5000;
   }

   h = h * 24;

   d = new Date().addHours(h);
}

Upvotes: 0

adeneo
adeneo

Reputation: 318302

Just get the number of days and add to the date object

var d    = new Date();
var s    = 9349859;
var days = Math.floor( s / 5000 );

d.setDate(d.getDate() + days); 

FIDDLE

Upvotes: 2

AMS
AMS

Reputation: 439

you absolutly want a loop ? cause I'd advise you to simply make a count number of caracters divised by the range you want (500) and add the number of hours required.

so no loops ...

Upvotes: 0

Related Questions