How to use Datetime Picker With Typescript

In my earlier post, How to use FullCalendar plugin with Typescript, i showed some typescript implementation showing use of FullCalendar. If you are using a calendar in your application then you are more than likely using some way for a user to enter date and time as well. In this post, I will show how to use Bootstrap DatetimePicker with Typescript. '

Component Installation

You are going to need following packages installed in your application.

Depending on your application platform, you can use NuGet package manager, Bower etc. to install these pre-requisites. Since I am using this in ASP.Net MVC application, I am using NuGet package manager. Datetime picker has dependency on moment.js package. If your installation does not install it automatically then make sure you manually install it in your application.

Following screenshots show the layout of user interface in my prototype implementation.

date picker
time picker

HTML Layout

Following snippet shows HTML layout of section of page that displays two instances of control. One is used to pick date component only. Second is used to pick time component only.

    <div class="col-sm-6">
        <div class="row">
            @Html.HiddenFor(m=>m.StartDate, new {id="auction_startdate"})
            <div class="col-sm-6">
                <div class="form-group">
                    <div class='input-group date' id='auctiondatepicker'>
                        <input type="text" class="form-control"/>
                        <span class="input-group-addon">
                            <span class="glyphicon glyphicon-calendar">
                            </span>
                        </span>
                    </div>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <div class='input-group date' id='auctiontimepicker'>
                        <input type="text" class="form-control"/>
                        <span class="input-group-addon">
                            <span class="glyphicon glyphicon-time">
                            </span>
                        </span>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-12">
                <button class="btn btn-primary" id="action_submit">Save</button>
                <button class="btn btn-primary" id="action_reset">Reset</button>
            </div>
        </div>
    </div>

Typescript Implementation

Following snippet shows how to use Datetime picker with Typescript.

    interface IAuction {
        name: string;
        startDate: number;
    }

    class PortalAuctionView {
    auctionDatePicker: BootstrapV3DatetimePicker.Datetimepicker;
    auctionTimePicker: BootstrapV3DatetimePicker.Datetimepicker;
    auctionStartDateInput: JQuery;

    constructor() {
        this.auctionDatePicker = $("#auctiondatepicker")
            .datetimepicker({
                useCurrent: false,
                format: "MM/DD/YYYY",
                minDate: moment()
            })
            .data("DateTimePicker");

        this.auctionTimePicker = $("#auctiontimepicker")
            .datetimepicker({
                format: "hh:mm A"
            })
            .data("DateTimePicker");

        this.auctionStartDateInput = $("#auction_startdate");
        const dateValue = this.auctionStartDateInput.val();
        if (dateValue.length > 0) {
            const startDate = moment(+dateValue);
            this.auctionDatePicker.date(startDate);
            this.auctionTimePicker.date(startDate);
        }

        _.bindAll(this, "save", "reset");
        $("#action_submit").on("click", this.save);
        $("#action_reset").on("reset", this.save);
    }

    save() {
        if (!this.validate()) {
            alert("Select start date");
            return;
        }
        // combine date and time picker values to construct date
        const dateText: string =
                `${this.auctionDatePicker.date().format("MM/DD/YYYY")}
                 ${this.auctionTimePicker.date().format("hh:mm")}`;
        const date = moment(dateText,"MM/DD/YYYY hh:mm");
        const requestData: IAuction = { name: "Phantom Drone Auction", startDate: date.unix() };
        alert(requestData);
    }

    reset() {
        this.auctionDatePicker.date(null);
        this.auctionTimePicker.date(null);
    }

    private validate() {
        return (this.auctionDatePicker.date() != null);
    }
}

$(() => {
    var auctionView = new PortalAuctionView();
});

The explanation of this implementation very simple. When document load is complete, instance of view is created. During construction of the view, the HTML elements for datetime picker and buttons are instantiated. You can see that typings for Datetime picker allow very strongly implementation and binding of data. The code reads the unix timestamp from a hidden field. That value is used to set initial values for date and time parts.

When use clicks on Save button, implementation reads date values set in two datetime picker controls. Since date and time components are being selected separately, you have to combine the values in two components to construct one date value. The implementation uses format function of Datetime picker to construct fully formatted date string in "MM/DD/YYYY hh:mm" format. That string is parsed to create moment object.

Pretty easy and straightforward to use Datetime picker with Typescript.

comments powered by Disqus

Search

Social

Weather

Monthly Posts