Friday, October 5, 2012

Convert string into a date, Add days to a date, Format date in different date format in JQuery

This article aims to explain writing a Javascript method (using JQuery functions) to achieve following:
- Convert a string into a date
- Add days to the date
- Format date into a valid date format

Prerequisites:
- JQuery library (For example, jquery-1.5.1.min.js, etc)

Source code:
<script type="text/javascript">
function ConvertToDate(strDate, dayPartIdx, monthPartIdx, yearPartIdx) {
//Pass dayPartIdx, monthPartIdx, yearPartIdx parameters depending upon the date format in strDate
//If its dd/mm/yy - pass 0,1,2 respectively.
        var day = strDate.split("/")[dayPartIdx],
        month = strDate.split("/")[monthPartIdx],
        year = strDate.split("/")[yearPartIdx];
        month = month - 1; //Date function considers 0 as January
        var convertedDate = new Date(year, month, day,0,0,0,0);
        return convertedDate;
    }

    function AddDaysToDate(strDate, numDays) {
        var dtDate = ConvertToDate(strDate, 0, 1, 2);
        var ms = dtDate.getTime() + (86400000 * numDays);
        return $.datepicker.formatDate('dd/mm/yy', new Date(ms));
    }
</script>

Sample call:
alert(AddDaysToDate('20/09/2012', 30));

P.S. - It is assumed that the passed string "strDate" is a valid date. However, you can add more validations to validate it before attempting to convert into a date.

1 comment:

Thanks for visiting my blog.
However, if this helped you in any way, please take a moment to write a comment.

Thanks
Nirman