1

The following code is used to get a date value and then add two hours to it. I would really like to know how to give a condition to add that two hours only between 08:30 in the morning until 18:30 of the evening and skip both the days ( Saturday,Sunday ).

For example: if the given date was in 17:30 of Tuesday so it followed the rule it will be ( 17:30 (of Tuesday ) + 2 = 09:30 ( of Wednesday-the next day) and if the given date was in 17:00 (of Friday) it will be if we skip the week-ends 09:00 ( of Monday-skip week-ends ) etc...

var now = new Date(Date.parse($(".x-form-hidden.x-form-field :eq(0)").val()));

now.setHours(now.getHours() + 2);

var dayVar = "";

if (now.getDate() < 10) {
    dayVar = 0 + "" + now.getDate()
} else {
    dayVar = now.getDate();
}

var dateString = 
    now.getFullYear() + "-" + 
    (now.getMonth() + 1) + "-" + 
    dayVar + " " + 
    now.getHours() + ":" + now.getMinutes() + ":0" + now.getSeconds();

$(".x-form-hidden.x-form-field :eq(1)").attr('value', dateString);
Nope
  • 22,147
  • 7
  • 47
  • 72

1 Answers1

1
function addTwoHours(date) {
    //date to decimal
    var day = date.getDay() - 1;
    var hour = date.getHours() - 8;
    var decimal = day * 10 + hour;

    //add two hours
    decimal += 2;

    //decimal to date
    var newDay = Math.floor(decimal / 10);
    var nextDay = newDay - day == 1;
    var weekEnd = newDay % 5 == 0;
    var newHour = (decimal % 10) + 8;
    var newDate = new Date(date.getTime() + (nextDay?24:0) * (weekEnd?3:1) * 60 * 60 * 1000);
    newDate.setHours(newHour);
    return  newDate;
}

Your time range represent 10 hours per day for 5 days a week, so it's easy to map to a continuous block of 50 hours. Considering then the units and tens gives the shift.

The following example gets the date for Friday 1 Feb. 17:15, which returns Monday 4 Feb 9:15. addTwoHours(new Date(2013, 1, 1, 17, 15));

Samuel
  • 2,106
  • 1
  • 17
  • 27
  • may i know how to use this function in PHP too, tnks http://stackoverflow.com/questions/20205963/php-add-two-hours-to-a-given-date – user1233875 Nov 26 '13 at 00:03