jnolte jnolte - 1 month ago 10
Javascript Question

Calculating Date in JavaScript

I am currently looking to calculate a custom date in JavaScript and my head is beginning to hurt thinking about it. I have a countdown clock that is to start every other Tuesday at 12pm. I have the countdown function working properly using the jQuery countdown plugin by Keith Wood but need assistance in calculating every other Tuesday of the month and having it reset on this day.

All help is greatly appreciated as always.

Thansk in advance

Answer

I've had to do something similar (not in JS but the algorithm is similar enough)

Now, before i start, to clarify i'm assuming this is something that happens fortnightly regardless of the length of the month, and not on the second and 4th Tuesday regardless of when it last happened, which is simpler to solve

Pick a date in the past that this event has occured on (or the date of the first occurrence) , we'll call this date base in the following code

var base=new Date('date of first occurrence');
var one_day=1000*60*60*24; //length of day in ms

// assume we care about if the countdown should start today 
// this may be different if you are building a calendar etc.
var date_to_check=new Date();

var diff_in_days=math.floor(date_to_check-base)/one_day);
var days_since_last_reset= diff_in_days%14;
if(days_since_last_reset == 0){
    //date_to_check is the same day in the fortnightly cycle as base
    //i.e. today at some point is when you'll want to show the timer
    //If you only want to show the timer between certain times,
    //add another check here
}else{
    //next reset in (14 - days_since_last_reset) days from date_to_check
}

Or the code-golf-esque version:

if( Math.floor((new Date()-new Date('date of first occurrence'))/1000/60/60/24)%14 == 0 )
    //reset/start timer