简体   繁体   中英

Get difference in days of two different dates in same ASPxDateEdit Control with javascript

I have an ASPxDateEdit control with this code:

<dx:ASPxDateEdit ID="dtPayDate" ClientInstanceName="dateEdit" EditFormatString="yyyy-MM-dd" DisplayFormatString="yyyy-MM-dd" runat="server" EnableClientSideAPI="true" CssClass="form-control">
<ClientSideEvents Init="FirstDate()" LostFocus="ChangeDate()" />

And two events:

var InititalPay;
var FinalPay;

function FirstDate(s, e) {
    var date = s.GetDate();
    var dd = date.getDate();
    var mm = date.getMonth();
    var yy = date.getFullYear();
    InitialPay = new Date(yy + ',' + mm + ',' + dd);
}

function ChangeDate() {
    var jsDate = dateEdit.GetDate();
    var year = jsDate.getFullYear(); // where getFullYear returns the year (four digits)
    var month = jsDate.getMonth(); // where getMonth returns the month (from 0-11)
    var day = jsDate.getDate(); // where getDate returns the day of the month (from 1-31)
    FinalPay = new Date(year + ',' + month + ',' + day);

    var a = moment([FinalPay]);
    var b = moment([InitialPay]);
    days = a.diff(b, 'days') // diferencia en dias
    alert(days)
}

I need to get the date before change and store in a var. Next get the date changed and store it into other var. Get the difference of two dates. I'm using moment.js too but if exists other method I can use it.

You need to use GotFocus event instead of Init :

<dx:ASPxDateEdit ID="dtPayDate" ClientInstanceName="dateEdit" EditFormatString="yyyy-MM-dd" DisplayFormatString="yyyy-MM-dd" runat="server" EnableClientSideAPI="true" CssClass="form-control">
    <ClientSideEvents GotFocus="FirstDate" LostFocus="ChangeDate"/>
</dx:ASPxDateEdit>

Also you can find the difference between two dates by using simple arifmethic.
Here is example:

var InitialDate;
var FinalDate;

function FirstDate(s, e) {
    InitialDate = s.GetDate();
}

function ChangeDate(s, e) {
    FinalDate = s.GetDate();

    if (!!InitialDate && !!FinalDate)
    {
        days = (FinalDate - InitialDate) / (1000 * 60 * 60 * 24);
        alert(days);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM