Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - variable previous business day

I'm trying to create a drop down list that will automatically enter dates into text fields.

The option "LBD" currently returns yesterday's date, however, I'd like it to return the date of the last business day. So that if today is Monday, it would return Friday's date, if today is Tuesday it would return Monday's date. So on and so forth.

This is what I've got so far:

Javascript:

<script>
$(document).ready(function() {
$("#datetype option").filter(function() {
    return $(this).val() == $("#datepickstart").val();
    return $(this).val() == $("#datepickend").val();
}).attr('selected', true);
    var d = new Date();
var yesterday = (d.getMonth() + 1) + "/" + (d.getDate() - 1) + "/" + d.getFullYear();
var today = (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
var fdm = (d.getMonth() + 1) + '/01/' + d.getFullYear();
var fdy = '01/01/' + new Date().getFullYear();
$("#datetype").on("change", function() {
    var selectedVal = $(this).find("option:selected").attr("value");
    if (selectedVal == 'LBD') {
        $("#datepickstart").val((yesterday));
        $("#datepickend").val((yesterday));
    }
    if (selectedVal == 'MtD') {
        $("#datepickstart").val(fdm);
        $("#datepickend").val(today);
    }
    if (selectedVal == 'YtD') {
        $("#datepickstart").val(fdy);
        $("#datepickend").val(today);
    }
});
})
</script>

html:

<select id="datetype" name="datetype"> 
<option value="">Please select...</option> 
<option value="LBD">LBD</option> 
<option value="MtD">MtD</option> 
<option value="YtD">YtD</option> 
</select>

<input type="text" id="datepickstart" name="datepickstart" value="">
<input type="text" id="datepickend" name="datepickend" value="">
like image 875
jwabsolution Avatar asked Jun 27 '16 13:06

jwabsolution


1 Answers

getDay() function is the key for your problem. I used @zzzzBov snippet for iterator. Below is my solution

step1:
   function isBusinessDay(date){
    var day = date.getDay();
    if(day == 0 || day == 6  ){
        return false;
    }
    return true;
    }


 step2:
    var date = new Date();
    while (!isBusinessDay(date)) { date.setDate(date.getDate() - 1) }

    console.log(date);//date always between monday to friday 

Hope this solves your problem. Happy coding!!

like image 83
ajay Avatar answered Sep 28 '22 17:09

ajay