Search code examples
javascriptwinjs

WINJS Timepicker how to


I have a service to which I receive two data (InTime & OutTime). These data are integer value in secs.

For example :

{
InTime :  36000,
OutTime : 57600
}

In my UI, I am using two TimePicker (WINJS.UI.Timepicker). In my timepicker I am using a 24 hour clock. I want to show these values in time picker. The values should be bound to time picker.

For example : In time should show me 10 : 00 and Out Time should show 16:00 in timepicker.

If user changes the value in time picker I should be bale to read that and convert that to seconds format so that I can do a post also.

So I have two problems:

  1. How to convert these received time (in seconds to time) so that I can set the time picker value in UI.

  2. When user changes, read the value from time picker, convert to seconds so that I can post it.

I have not been able to understand the TimePicker completely (Yes I have seen the samples), so I am having some issues here.

For the conversion, is there any javascript function already available ?

Any help appreciated.

  • Girija

Solution

  • For you to convert the seconds to time format you can use the following javascript function

    function secondsToTime(secs)
    {
        var hours = Math.floor(secs / (60 * 60));
    
        var divisor_for_minutes = secs % (60 * 60);
        var minutes = Math.floor(divisor_for_minutes / 60);
    
        var divisor_for_seconds = divisor_for_minutes % 60;
        var seconds = Math.ceil(divisor_for_seconds);
    
        var obj = {
            "h": hours,
            "m": minutes,
            "s": seconds
        };
        return obj;
    }
    

    To display time in time picker ,you can set it in current property

    <div data-win-control="WinJS.UI.TimePicker" data-win-options="{current='your value'}">
    </div>
    

    To detect user input and get value from time picker you can you need to register onchange event handler..

    timePicker.onchange = hourChangeHandler; 
    
    function hourChangeHandler(event) {
        // Insert code here.
        }
    

    Once you get the time from user you can convert it to seconds using this function

    var hms = '02:04:33';   // your input string
    var a = hms.split(':'); // split it at the colons
    
    // minutes are worth 60 seconds. Hours are worth 60 minutes.
    var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]); 
    

    This is to give you a start, you can change the data types and time format as per your requirements..