How to get difference between two dates and convert to number of days using vuejs?

I am in new to vue js. i am working on .net core application with vue js. I want to caluculate difference of two dates and convert to number of days dynamically.
Another requirement is same but if user add number of days from input text then i need to update my date and total number of days in input text.
Any help highly appreciated.
This is my html page code.

<div id="basic-data-app" v-cloak>
    <partial name="_ProductForm"/>
    <partial name="_DeveloperForm"/>
    <partial name="_ConsualtantForm"/>
    <partial name="_ContractorForm"/>
    
	<div class="row">
		<div class="col-md-3 col-sm-12">
			<div class="form-group">
				<label> المشروع</label>
				<input type="text" class="form-control" v-model="model.ProjectName" readonly>

			</div>
		</div>
		<div class="col-md-3 col-sm-12" v-if="Project.LKProjectTypeID==2">
			<div class="form-group">
				<label>المطور</label>
				<select class="form-control" v-model="model.ProjectDeveloperID">
					<option value="0">اختر ...</option>
					<option v-for="l in Developers" :value="l.Key">{{l.Value}}</option>
				</select>
				<button type="button" class="btn main__btn" @@click="showDevForm()" style=" left: 18px;top: 32px;min-width: 30px;">
					<i class="fa fa-plus" style="color:#fff"></i>

				</button>
				<span class="text-danger">{{errors.ProjectDeveloperID}}</span>
			</div>
		</div>
		<div class="col-md-3 col-sm-12">
			<div class="form-group">
				<label>الاستشاري</label>
				<select class="form-control" v-model="model.ProjectConsultantID">
					<option value="0">اختر ...</option>
					<option v-for="l in Consultants" :value="l.Key">{{l.Value}}</option>
				</select>
				<button type="button" class="btn main__btn" @@click="showConsForm()" style="left: 18px;top: 32px;min-width: 30px;">
					<i class="fa fa-plus" style="color:#fff"></i>

				</button>
				<span class="text-danger">{{errors.ProjectConsultantID}}</span>
			</div>
		</div>
		<div class="col-md-3 col-sm-12">
			<div class="form-group">
				<label>المقاول</label>
				<select class="form-control" v-model="model.ProjectContractorID">
					<option value="0">اختر ...</option>
					<option v-for="l in Contractors" :value="l.Key">{{l.Value}}</option>
				</select>
				<button type="button" class="btn main__btn" @@click="showContForm()" style=" left: 18px;top: 32px;min-width: 30px;">
					<i class="fa fa-plus" style="color:#fff"></i>

				</button>
				<span class="text-danger">{{errors.ProjectContractorID}}</span>
			</div>
		</div>
		<div class="col-md-3 col-sm-12">
			<div class="form-group">
				<label>منتجات المشروع</label>
				<input type="text" class="form-control" v-model="Project.Products">
				@*<input type="text" class="form-control" v-model="Project.Products">*@

			</div>
		</div>
		<div class="col-md-3 col-sm-12">
			<div class="form-group">
				<label>عدد المنتجات</label>
				@*<input type="text" class="form-control" :value="Project.ProductsCount" readonly>*@
				<input type="text" class="form-control" :value="Project.ProductsCount">
				@*<input type="text" class="form-control" v-model="Project.ProductsCount" />*@
				<span class="text-danger">{{errors.ProductsCount}}</span>
				@*<button type="button" class="btn main__btn" @@click="showForm()" style="position: absolute; left: 18px;top: 32px;min-width: 30px;">
				<i class="fa fa-plus" style="color:#fff"></i>

				</button>*@
			</div>
		</div>
		<div class="col-md-3 col-sm-12" v-if="Project.LKProjectTypeID==2">
			<div class="form-group">
				<label>تاريخ بداية البيع</label>
				<input type="date" class="form-control" name="landOwner" v-model="model.SellStartDate">
				<span class="text-danger">{{errors.SellStartDate}}</span>
			</div>
		</div>
		<div class="col-md-3 col-sm-12" v-if="Project.LKProjectTypeID==2">
			<div class="form-group">
				<label>حالة رخصة البيع</label>
				<select class="form-control" v-model="model.LksellLicenseStatusID">
					<option value="0">اختر ...</option>
					<option v-for="l in SellLicenseStatus" :value="l.Key">{{l.Value}}</option>
				</select>
				<span class="text-danger">{{errors.LksellLicenseStatusID}}</span>
			</div>
		</div>
		<div class="col-md-3 col-sm-12">
			<div class="form-group">
				<label>حالة رخصة البناء</label>
				<select class="form-control" v-model="model.LkbuildingLicenseStatusID">
					<option value="0">اختر ...</option>
					<option v-for="l in BuildingLicenseStatus" :value="l.Key">{{l.Value}}</option>
				</select>
				<span class="text-danger">{{errors.LkbuildingLicenseStatusID}}</span>
			</div>
		</div>
		<div class="col-md-3 col-sm-12">
			<div class="form-group">
				<label>رقم العقد</label>
				<input type="text" class="form-control" v-model="model.ContractNo">
				<span class="text-danger">{{errors.ContractNo}}</span>
			</div>
		</div>
		<div class="col-md-3 col-sm-12">
			<div class="form-group">
				<label>تاريخ توقيع العقد</label>
				<input type="date" class="form-control" v-model="model.ContractSignDate" />
				<span class="text-danger">{{errors.ContractSignDate}}</span>
			</div>
		</div>
		<div class="col-md-3 col-sm-12">
			<div class="form-group">
				<label>تاريخ نهاية العقد</label>
				<input type="date" class="form-control" v-model="model.ContractEndDate" />
				<span class="text-danger">{{errors.ContractEndDate}}</span>
			</div>
		</div>
		<div class="col-md-3 col-sm-12">
			<div class="form-group">
				<label>تاريخ بداية المشروع</label>
				<input type="date" class="form-control" v-model="model.ProjectStartDate" />
				<span class="text-danger">{{errors.ProjectStartDate}}</span>
			</div>
		</div>
		<div class="col-md-3 col-sm-12">
			<div class="form-group">
				<label>تاريخ نهاية المشروع</label>
				<input type="date" class="form-control" v-model="model.ProjectEndDate" />
				<span class="text-danger">{{errors.ProjectEndDate}}</span>
			</div>
		</div>
		<div class="col-md-3 col-sm-12">
			<div class="form-group">
				<label>مدة التنفيذ التعاقدية</label>
				<input type="text" id="ContractualExecutionPeriod1" class="form-control" v-model="model.ContractualExecutionPeriod">
				<span class="text-danger">{{errors.ContractualExecutionPeriod}}</span>
			</div>
		</div>
		<div class="col-md-3 col-sm-12">
			<div class="form-group">
				<label>مدة التنفيذ الاجمالية</label>
				<input type="text" class="form-control" v-model="model.TotalExecutionPeriod" />
				<span class="text-danger">{{errors.TotalExecutionPeriod}}</span>
			</div>
		</div>
		<div class="col-md-3 col-sm-12">
			<div class="form-group">
				<label>مدة التمديد</label>
				<input type="text" class="form-control" v-model="model.ExtensionDuration" />
				<span class="text-danger">{{errors.ExtensionDuration}}</span>
			</div>
		</div>
		<button type="button" class="btn main__btn pull-left" @@click="CalDate()">

			Calculate
		</button>
		<div class="col-md-3 col-sm-12">
			<div class="form-group">
				<label>حالة المخطط العام</label>
				<select class="form-control" v-model="model.LkstatusOfGeneralOutlineId">
					<option value="0">اختر ...</option>
					<option v-for="l in StatusOfGeneralOutline" :value="l.Key">{{l.Value}}</option>
				</select>
				<span class="text-danger">{{errors.LkstatusOfGeneralOutlineId}}</span>
			</div>
		</div>
		<div class="col-md-12">
			<div class="form-group">
				<label>ملاحظات</label>
				<textarea class="form-control" v-model="model.Notes"></textarea>
				<span class="text-danger" id="cityError"></span>
			</div>
		</div>
	</div>
    <button type="button" class="btn main__btn" @@click="save()">حفظ</button>

</div>
     ```                                                                     
     
```javascript
basicApp = new Vue({
    el: '#basic-data-app',
    data: {
        Project: {},
        model: { ProjectDeveloperID: 0, ProjectConsultantID: 0, ProjectContractorID: 0, LksellLicenseStatusID: 0, LKBuildingLicenseStatusID: 0, LkstatusOfGeneralOutlineId: 0 },
        errors: {},
        basic_saved: false,
        Developers: [],
        Consultants: [],
        Contractors: [],
        SellLicenseStatus: [],
        BuildingLicenseStatus: [],
        StatusOfGeneralOutline: [],
        pro_errors: [],
        product: { ProductID: 0, Describition: "" },
        Products: [],
        dev_errors: [],
        developer: { LKDeveloperID: 0, LKDeveloperCode: "" },
        LKDevelopers: DEVELOPERS,

        cons_errors: [],
        consultant: { LKConsultantID: 0, LKConsultantCode: "" },
        LKConsultants: CONSULTANTS,

        cont_errors: [],
        contractor: { LKContractorID: 0, LKContractorCode: "" },
        LKContractors: CONTRACTORS,

    },
    methods: {
        loadLookups: function () {
            let self = this;
            var projectId = +getQueryVariable("projectID");
            waitLoader();
            axios.get(`/api/BasicData/Lookups/${projectId}`)
                .then(function (res) {
                    let vm = res.data;
                    self.Developers = vm.find(e => e.Type == 'Developers').Data;
                    self.LKDevelopers = DEVELOPERS.filter(d => self.Developers.map(e => e.Value).indexOf(d.LKDeveloperName) < 0);
                    self.Consultants = vm.find(e => e.Type == 'Consultants').Data;
                    self.LKConsultants = CONSULTANTS.filter(d => self.Consultants.map(e => e.Value).indexOf(d.LKConsultantName) < 0);
                    self.Contractors = vm.find(e => e.Type == 'Contractors').Data;
                    self.LKContractors = CONTRACTORS.filter(d => self.Contractors.map(e => e.Value).indexOf(d.LKContractorName) < 0);
                    self.SellLicenseStatus = vm.find(e => e.Type == 'SellLicenseStatus').Data;
                    self.BuildingLicenseStatus = vm.find(e => e.Type == 'BuildingLicenseStatus').Data;
                    self.StatusOfGeneralOutline = vm.find(e => e.Type == 'StatusOfGeneralOutline').Data;
                    self.Products = vm.find(e => e.Type == 'Products').Data;
                    waitLoader(false)
                })
                .catch(function (err) {
                    console.log(err);
                    waitLoader(false)
                });
        },
        getProject: function () {
            let self = this;
            var projectId = +getQueryVariable("projectID")
            waitLoader()
            axios.get(`/api/BasicData/Projects/${projectId}`)
                .then(function (res) {
                    let vm = res.data;
                    self.Project = vm;

                    if (vm.BasicData != null && vm.BasicData != "") {
                        self.model = JSON.parse(vm.BasicData);
                        localStorage.setItem("basic", "1");
                    }

                    self.model.ProjectName = vm.ProjectName;
                    waitLoader(false)
                })
                .catch(function (err) {
                    console.log(err);
                    waitLoader(false)
                });
        },
        save: function () {
            let self = this;
            if (!self.isValid()) {
                return;
            }
            let projectId = +getQueryVariable("projectID");
            self.model.ProjectID = projectId;
            waitLoader()
            axios.post(`/api/BasicData`, self.model)
                .then(function (res) {
                    let vm = res.data;
                    self.basic_saved = true;
                    waitLoader(false)
                    localStorage.setItem("basic", "1")
                    $.notify("تم الحفظ بنجاح", 'success')
                }).catch(function (err) {
                    console.log(err);
                    self.basic_saved = false;
                    localStorage.setItem("basic", "0")
                    waitLoader(false)
                    $.notify("حدث خطأ أثناء الحفظ .. من فضلك حاول مرة أخرى", 'error')
                });
        },
        isValid: function () {
            let self = this;
            self.errors = {};
            if (!self.model.ContractEndDate || self.model.ContractEndDate == "") {
                self.errors.ContractEndDate = "يجب إدخال تاريخ العقد";
            }

            if (!self.model.ContractNo || self.model.ContractNo == "") {
                self.errors.ContractNo = "يجب إدخال رقم العقد";
            }

            if (!self.model.ContractSignDate || self.model.ContractSignDate == "") {
                self.errors.ContractSignDate = "يجب إدخال تاريخ توقيع العقد";
            }

            if (!self.model.ProjectStartDate || self.model.ProjectStartDate == "") {
                self.errors.ProjectStartDate = "يجب إدخال تاريخ بداية المشروع";
            }

            if (!self.model.ProjectEndDate || self.model.ProjectEndDate == "") {
                self.errors.ProjectEndDate = "يجب إدخال تاريخ نهاية المشروع";
            }

            if (!self.model.ContractualExecutionPeriod || self.model.ContractualExecutionPeriod == "") {
                self.errors.ContractualExecutionPeriod = "يجب إدخال مدة التنفيذ ";
            }

            if (!self.model.TotalExecutionPeriod || self.model.TotalExecutionPeriod == "") {
                self.errors.TotalExecutionPeriod = "يجب إدخال مدة التنفيذ الاجمالية";
            }

            if (!self.model.ExtensionDuration || self.model.ExtensionDuration == "") {
                self.errors.ExtensionDuration = "يجب إدخال مدة التمديد ";
            }

            if (!self.model.LkbuildingLicenseStatusID || self.model.LkbuildingLicenseStatusID == "") {
                self.errors.LkbuildingLicenseStatusID = "يجب إختيار حالة رخصة البناء ";
            }

            if ((!self.model.LksellLicenseStatusID || self.model.LksellLicenseStatusID == "") && self.Project.LKProjectTypeID == 2) {
                self.errors.LksellLicenseStatusID = "يجب إختيار حالة رخصة البيع ";
            }

            if (!self.model.LkstatusOfGeneralOutlineId || self.model.LkstatusOfGeneralOutlineId == "") {
                self.errors.LkstatusOfGeneralOutlineId = "يجب إختيار حالة المخطط العام ";
            }

            if (!self.model.ProjectConsultantID || self.model.LkstatusOfGeneralOutlineId == 0) {
                self.errors.ProjectConsultantID = "يجب إختيار الاستشاري ";
            }

            if (!self.model.ProjectContractorID || self.model.ProjectContractorID == 0) {
                self.errors.ProjectContractorID = "يجب إختيار المقاول ";
            }


            if ((!self.model.ProjectDeveloperID || self.model.ProjectDeveloperID == 0) && self.Project.LKProjectTypeID == 2) {
                self.errors.ProjectDeveloperID = "يجب إختيار المطور ";
            }



            if ((!self.model.SellStartDate || self.model.SellStartDate == "") && self.Project.LKProjectTypeID == 2) {
                self.errors.SellStartDate = "يجب إدخال تاريخ بداية البيع ";
            }

            return Object.keys(self.errors).length == 0;
        },
        // Project Functions
        showForm: function () {
            var self = this;
            self.product = { ProductID: 0, Describition: "" }
            $('#form-title').text('إضافة');
            $('#product-form')
                .modal({ backdrop: 'static', keyboard: false })
                .show();
        },
        closeForm: function () {
            var self = this;
            self.product = { ProductID: 0, Describition: "" }
            pro_errors = [];
            $('#form-title').text('إضافة');
            $('#product-form').modal('hide');
        },
        addProject: function () {
            let self = this;
            self.product.ProjectID = +getQueryVariable("projectID");
            waitLoader()
            axios.post(`/api/BasicData/Products`, self.product)
                .then(function (res) {
                    let vm = res.data;
                    var products = self.Project.Products.split(' - ');
                    var pCounts = +self.Project.ProductsCount;
                    products.push(vm.Product);
                    self.Project.ProductsCount = pCounts + 1;
                    self.Project.Products = products.join(' - ');
                    self.closeForm();
                    waitLoader(false)
                    $.notify("تم الحفظ بنجاح", 'success')
                }).catch(function (err) {
                    console.log(err);
                    waitLoader(false)
                    $.notify("حدث خطأ أثناء الحفظ .. من فضلك حاول مرة أخرى", 'error')
                });
        },
        // Developer Functions
        showDevForm: function () {
            var self = this;
            self.developer = { LKDeveloperID: 0, LKDeveloperCode: "" }
            $('#dev-form-title').text('إضافة مطور');
            $('#developer-form')
                .modal({ backdrop: 'static', keyboard: false })
                .show();
        },
        closeDevForm: function () {
            var self = this;
            self.developer = { LKDeveloperID: 0, LKDeveloperCode: "" }
            self.dev_errors = [];
            $('#dev-form-title').text('إضافة مطور');
            $('#developer-form').modal('hide');
        },
        addDeveloper: function () {
            let self = this;
            self.developer.ProjectID = +getQueryVariable("projectID");
            waitLoader()
            axios.post(`/api/BasicData/Developers`, self.developer)
                .then(function (res) {
                    let vm = res.data;
                    self.Developers.push(vm);
                    self.LKDevelopers = DEVELOPERS.filter(d => self.Developers.map(e => e.Value).indexOf(d.LKDeveloperName) < 0);
                    self.model.ProjectDeveloperID = vm.Key;
                    self.closeDevForm();
                    waitLoader(false)
                    $.notify("تم الحفظ بنجاح", 'success')
                }).catch(function (err) {
                    console.log(err);
                    waitLoader(false)
                    $.notify("حدث خطأ أثناء الحفظ .. من فضلك حاول مرة أخرى", 'error')
                });
        },
        // Consultants Functions
        showConsForm: function () {
            var self = this;
            self.consultant = { LKConsultantID: 0, LKConsultantCode: "" }
            $('#cons-form-title').text('إضافة استشاري');
            $('#cons-form')
                .modal({ backdrop: 'static', keyboard: false })
                .show();
        },
        closeConsForm: function () {
            var self = this;
            self.consultant = { LKConsultantID: 0, LKConsultantCode: "" }
            self.cont_errors = [];
            $('#cons-form-title').text('إضافة استشاري');
            $('#cons-form').modal('hide');
        },
        addConsultant: function () {
            let self = this;
            self.consultant.ProjectID = +getQueryVariable("projectID");
            waitLoader()
            axios.post(`/api/BasicData/Consultants`, self.consultant)
                .then(function (res) {
                    let vm = res.data;
                    self.Consultants.push(vm);
                    self.LKConsultants = CONSULTANTS.filter(d => self.Consultants.map(e => e.Value).indexOf(d.LKConsultantName) < 0);
                    self.model.ProjectConsultantID = vm.Key;
                    self.closeConsForm();
                    waitLoader(false)
                    $.notify("تم الحفظ بنجاح", 'success')
                }).catch(function (err) {
                    console.log(err);
                    waitLoader(false)
                    $.notify("حدث خطأ أثناء الحفظ .. من فضلك حاول مرة أخرى", 'error')
                });
        },
        // Consultants Functions
        showContForm: function () {
            var self = this;
            self.contractor = { LKContractorID: 0, LKContractorCode: "" };
            $('#cont-form-title').text('إضافة مقاول');
            $('#cont-form')
                .modal({ backdrop: 'static', keyboard: false })
                .show();
        },
        closeContForm: function () {
            var self = this;
            self.contractor = { LKContractorID: 0, LKContractorCode: "" };
            self.cont_errors = [];
            $('#cont-form-title').text('إضافة مقاول');
            $('#cont-form').modal('hide');
        },
        addContractor: function () {
            let self = this;
            self.contractor.ProjectID = +getQueryVariable("projectID");
            waitLoader()
            axios.post(`/api/BasicData/Contractors`, self.contractor)
                .then(function (res) {
                    let vm = res.data;
                    self.Contractors.push(vm);
                    self.LKContractors = CONTRACTORS.filter(d => self.Contractors.map(e => e.Value).indexOf(d.LKContractorName) < 0);
                    self.model.ProjectContractorID = vm.Key;
                    self.closeContForm();
                    waitLoader(false)
                    $.notify("تم الحفظ بنجاح", 'success')
                }).catch(function (err) {
                    console.log(err);
                    waitLoader(false)
                    $.notify("حدث خطأ أثناء الحفظ .. من فضلك حاول مرة أخرى", 'error')
                });
        },

    },
    computed: {},
    watch: {
        'developer.LKDeveloperCode': function (n, o) {
            let self = this;
            var dev = self.LKDevelopers.find(e => e.LKDeveloperCode.toLowerCase() == n.toLowerCase());
            if (dev) {
                self.developer = dev;
            }
        },
        'consultant.LKConsultantCode': function (n, o) {
            let self = this;
            var cons = self.LKConsultants.find(e => e.LKConsultantCode.toLowerCase() == n.toLowerCase());
            if (cons) {
                self.consultant = cons;
            }
        },
        'contractor.LKContractorCode': function (n, o) {
            let self = this;
            var cont = self.LKContractors.find(e => e.LKContractorCode.toLowerCase() == n.toLowerCase());
            if (cont) {
                self.contractor = cont;
            }
        }

    },
    beforeMount() { },
    mounted() { },
    created() {
        try {
            this.loadLookups();
            this.getProject();
        } catch (e) { }
    }
});

The code provided is currently not properly formatted for this forum. In its current state it’s illegible which makes it hard for people to help you.

Please read the following guide about how to properly format code and then edit your topic accordingly.

Thanks!

Recommend a very useful date/time util library: momentjs. Which can help to solve basically all your problems.

1 Like

Other one I think it’s OK too is date-fns.
:smiley:

1 Like